ZGDD/chat-robot
1
1# -*- coding: utf-8 -*-2"""robot-chat.ipynb3 4Automatically generated by Colaboratory.5 6Original file is located at7 https://colab.research.google.com/drive/1I8kKT0soc2288I5sVj3dIr-f1QbRwPKz8"""9import openai10import os11import gradio as gr12 13openai.api_key = os.environ.get("OPENAI_API_KEY")14 15class Conversation:16 def __init__(self, prompt, num_of_round):17 self.prompt = prompt18 self.num_of_round = num_of_round19 self.messages = []20 self.messages.append({"role": "system", "content": self.prompt})21 22 def ask(self, question):23 try:24 self.messages.append( {"role": "user", "content": question})25 response = openai.ChatCompletion.create(26 model="gpt-3.5-turbo",27 messages=self.messages,28 temperature=0.5,29 max_tokens=2048,30 top_p=1,31 )32 except Exception as e:33 print(e)34 return e35 36 message = response["choices"][0]["message"]["content"]37 self.messages.append({"role": "assistant", "content": message})38 39 if len(self.messages) > self.num_of_round*2 + 1:40 del self.messages[1:3]41 return message42 43 44prompt = """你是一个问答机器人,你的回答需要满足以下要求:451. 你的回答必须是中文462. 回答限制在100个字以内"""47 48conv = Conversation(prompt, 5)49 50def predict(input, history=[]):51 history.append(input)52 response = conv.ask(input)53 history.append(response)54 responses = [(u,b) for u,b in zip(history[::2], history[1::2])]55 return responses, history56 57with gr.Blocks(css="#chatbot{height:350px} .overflow-y-auto{height:500px}") as chatRobot:58 chatbot = gr.Chatbot(elem_id="chatbot")59 state = gr.State([])60 61 with gr.Row():62 txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)63 64 txt.submit(predict, [txt, state], [chatbot, state])65 66chatRobot.launch()