File size: 2,338 Bytes
0ef7602
10c1657
39ee2a2
1d54e0d
10c1657
 
 
 
 
 
 
0ef7602
10c1657
 
0ef7602
10c1657
 
 
 
 
 
 
 
 
0ef7602
10c1657
 
 
 
 
0ef7602
 
10c1657
0ef7602
 
10c1657
 
0ef7602
10c1657
 
 
 
 
0ef7602
 
10c1657
 
 
 
 
0ef7602
10c1657
0ef7602
10c1657
 
 
 
 
 
 
 
0ef7602
 
10c1657
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
# Import necessary libraries
import os 
import time

import openai
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")

import gradio as gr

# Create an empty list to store chat messages
messages = []

# Function to add user's text to chat history
def add_user_text(chat_history, user_text):
    print('user_text_from_typing: ', user_text)

    global messages
    messages += [{"role":'user', 'content': user_text}]

    chat_history = chat_history + [(user_text, None)]
    return chat_history, gr.update(value="", interactive=False)

# Function for the bot to respond
def bot_respond(chat_history, openai_gpt_key):
    global messages

    if openai_gpt_key is not "":
        openai.api_key = openai_gpt_key

    # Generate response from OpenAI Chat API
    bot_response = openai.ChatCompletion.create(
            model='gpt-3.5-turbo',
            messages=messages,
        )
    bot_text = bot_response["choices"][0]["message"]["content"]
    print("bot_text: ", bot_text)

    messages = messages + [{"role":'assistant', 'content': bot_text}]

    print(chat_history)
    chat_history[-1][1] = ""

    # Yield the chat history with the bot's response character by character
    for character in bot_text:
        chat_history[-1][1] += character
        time.sleep(0.02)
        yield chat_history

# Create a Gradio interface
with gr.Blocks() as demo:
    openai_gpt_key = gr.Textbox(label="OpenAI GPT API Key", value="", placeholder="sk..", info="If an error is raised, you need to provide your own GPT keys for this app to function properly")
    clear_btn = gr.Button("Clear for Restart")
    chat_history = gr.Chatbot([], elem_id="chat_history").style(height=500)

    with gr.Box():
        user_text = gr.Textbox(
            show_label=False,
            placeholder="Enter text and press enter",
        ).style(container=False)

    # Handle user input and bot response
    user_text.submit(
        add_user_text, [chat_history, user_text], [chat_history, user_text], queue=False).then(
            bot_respond, [chat_history, openai_gpt_key], chat_history).then(
                lambda: gr.update(interactive=True), None, [user_text], queue=False)

    clear_btn.click(lambda: None, None, chat_history, queue=False)

if __name__ == "__main__":
    demo.queue()
    demo.launch()