Spaces:
Running
Running
File size: 2,236 Bytes
476489a 4740dd6 476489a 4740dd6 476489a 4740dd6 476489a 4740dd6 476489a 4740dd6 476489a 4740dd6 |
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 |
import gradio as gr
import os
import requests
import json
api_key = os.environ.get("OPENAI_API_KEY")
def openai_chat(prompt, history):
if not prompt:
return gr.update(value='', visible=len(history) < 10), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], 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 gr.update(value='', visible=len(history) < 10), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], history
def start_new_conversation(history):
history = []
return gr.update(value=None, visible=True), gr.update(value=[]), 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.
Current limit is 5 messages per conversation.""",
elem_id="header")
chatbot = gr.Chatbot(elem_id="chatbox")
input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False)
btn_start_new_conversation = gr.Button("Start a new conversation")
input_message.submit(openai_chat, [input_message, history], [input_message, chatbot, history])
btn_start_new_conversation.click(start_new_conversation, [history], [input_message, chatbot, history])
if __name__ == "__main__":
demo.launch(debug=True, height='800px')
|