File size: 1,573 Bytes
476489a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
import requests
import json

api_key = os.environ.get("OPENAI_API_KEY")

def openai_chat(prompt, history):

    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    prompt_msg = {
                "role": "user",
                "content": prompt
            }
    
    data = {
        "model": "gpt-3.5-turbo",
        "messages": history + [prompt_msg]
    }

    response = requests.post(url, headers=headers, json=data)
    json_data = json.loads(response.text)

    response = json_data["choices"][0]["message"]

    history.append(prompt_msg)
    history.append(response)

    return None, [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], history

css = """
      #col-container {max-width: 50%; margin-left: auto; margin-right: auto;}
      #chatbox {min-height: 400px;}
      #header {text-align: center;}
      """

with gr.Blocks(css=css) as demo:
    history = gr.State([])

    with gr.Column(elem_id="col-container"):
        gr.Markdown("""## OpenAI Chatbot Demo
                    Using the ofiicial API and GPT-3.5 Turbo model""", elem_id="header")
        chatbot = gr.Chatbot(elem_id="chatbox")
        input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)

    input_message.submit(openai_chat, [input_message, history], [input_message, chatbot, history])
            
if __name__ == "__main__":
    demo.launch()