File size: 1,505 Bytes
804ba71
 
da67f32
 
804ba71
da67f32
 
804ba71
da67f32
 
 
 
 
 
 
 
 
 
 
7289133
da67f32
 
 
 
 
 
 
7289133
da67f32
 
 
 
 
 
 
7289133
da67f32
 
 
 
 
 
 
7289133
da67f32
 
 
 
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
import gradio as gr
import openai
import random
import time

# Set up OpenAI API key
openai.api_key = "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"

system_message = {"role": "system", "content": "You are a helpful assistant."}

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.Button("Clear")

    state = gr.State([])

    def user(user_message, history):
        return "", history + [[user_message, None]]

    def bot(history, messages_history):
        user_message = history[-1][0]
        bot_message, messages_history = ask_gpt(user_message, messages_history)
        messages_history += [{"role": "assistant", "content": bot_message}]
        history[-1][1] = bot_message
        time.sleep(1)
        return history, messages_history

    def ask_gpt(message, messages_history):
        messages_history += [{"role": "user", "content": message}]
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=messages_history
        )
        return response['choices'][0]['message']['content'], messages_history

    def init_history(messages_history):
        messages_history = []
        messages_history += [system_message]
        return messages_history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, [chatbot, state], [chatbot, state]
    )

    clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state], [state])

demo.launch()