CoolFace
Apppublic

zealhugh/Chat_Bot

sourceHugging Faceapache-2.0updated 2y agoView on Hugging Face
0likes
app.py59 linesDownload Raw Back to root
1from openai import OpenAI2import os3 4client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])5 6 7class Conversation:8    def __init__(self, prompt, num_of_round):9        self.prompt = prompt10        self.num_of_round = num_of_round11        self.messages = []12        self.messages.append({"role": "system", "content": self.prompt})13 14    def ask(self, question):15        try:16            self.messages.append({"role": "user", "content": question})17            response = client.chat.completions.create(18                model="gpt-4o-mini",19                messages=self.messages,20                temperature=0.5,21                max_tokens=2048,22                top_p=1,23            )24        except Exception as e:25            print(e)26            return e27 28        message = response.choices[0].message.content29        self.messages.append({"role": "assistant", "content": message})30 31        if len(self.messages) > self.num_of_round*2 + 1:  # sytem+n*(user+assistant)32            del self.messages[1:3] #Remove the first round conversation left.33        return message34 35 36import gradio as gr37prompt = """你是一个美食鉴赏家,用中文回答关于美食的问题。你的回答需要满足以下要求:381. 你的回答必须是中文392. 回答限制在100个字以内"""40 41conv = Conversation(prompt, 10)42 43def answer(question, history=[]):44    history.append(question)45    response = conv.ask(question)46    history.append(response)47    responses = [(u,b) for u,b in zip(history[::2], history[1::2])]48    return responses, history49 50with gr.Blocks(css="#chatbot{height:300px} .overflow-y-auto{height:500px}") as demo:51    chatbot = gr.Chatbot(elem_id="chatbot")52    state = gr.State([])53 54    with gr.Row():55        txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter")56 57    txt.submit(answer, [txt, state], [chatbot, state])58 59demo.launch()