File size: 1,778 Bytes
32506e1
 
 
 
 
 
ca58969
32506e1
 
 
 
 
 
 
 
 
ca58969
32506e1
 
 
 
 
 
 
 
 
 
 
 
 
ca58969
 
32506e1
 
ca58969
 
32506e1
 
 
 
 
 
 
ca58969
32506e1
 
 
 
 
ca58969
32506e1
 
 
 
 
 
 
 
 
 
 
 
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
63
import openai
import os
import gradio as gr

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-16k-0613",
                messages=self.messages,
                temperature=0,
                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]
        return message


with open('chatbot_03_prompt.md', 'r') as file:
    prompt = file.read()

prompt = '"""\n' + prompt + '\n"""'

conv = Conversation(prompt, 5)


def respond(message, chat_history):
    bot_message = conv.ask(message)
    chat_history.append((message, bot_message))
    return "", chat_history


init_conversation = [(None, "欢迎来到 recon! 请问有什么可以帮助你的吗?")]

with gr.Blocks(css="#chatbot{height:700px} .overflow-y-auto{height:900px}") as demo:
    chatbot = gr.Chatbot(elem_id="chatbot", value=init_conversation, height="700px")
    state = gr.State([])

    with gr.Row():
        msg = gr.Textbox(show_label=False, placeholder="Enter text and press enter")

    msg.submit(respond, [msg, chatbot], [msg, chatbot])

demo.launch()