File size: 1,798 Bytes
51ebb68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os,openai
import gradio as gr

class Conversation:
    def __init__(self,prompt,num_of_round):
        self.prompt = prompt
        self.num_of_round = num_of_round
        self.message = []
        self.message.append({'role':'system','content':self.prompt})

    def ask(self,question):
        try:
            self.message.append({'role':'user','content':question})
            response = openai.ChatCompletion.create(
                model = 'gpt-3.5-turbo',
                message=self.message,
                temperature = 0.5,
                max_tokens=2048,
                top_p=1
            )

        except Exception as e:
            print(e)
            return e

        message = response['choices'][0]['message']['content']
        num_of_tokens = response['usage']['total_tokens']
        self.message.append({'role':'assistant','content': message})

        if len(self.message) > self.num_of_round *2-1:
            del self.message[1:3]
        return message,num_of_tokens


prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
1. 你的回答必须是中文
2. 回答限制在100个字以内"""

conv = Conversation(prompt,10)

def answer(question,history=[]):
    history.append(question)
    response = conv.ask(question)
    history.append(response)
    response = [(u,b) for u ,b in zip(history[::2],history[1::2])]
    return response,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 = 'Enter text and press enter').style(container=False)

    txt.submit(answer,[txt,state],[chatbot,state])

demo.launch()