chatgpt-demo / app.py
anzorq's picture
init
476489a
raw
history blame
1.57 kB
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()