Spaces:
Running
Running
init
Browse files
app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
api_key = os.environ.get("OPENAI_API_KEY")
|
| 7 |
+
|
| 8 |
+
def openai_chat(prompt, history):
|
| 9 |
+
|
| 10 |
+
url = "https://api.openai.com/v1/chat/completions"
|
| 11 |
+
headers = {
|
| 12 |
+
"Content-Type": "application/json",
|
| 13 |
+
"Authorization": f"Bearer {api_key}"
|
| 14 |
+
}
|
| 15 |
+
prompt_msg = {
|
| 16 |
+
"role": "user",
|
| 17 |
+
"content": prompt
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
data = {
|
| 21 |
+
"model": "gpt-3.5-turbo",
|
| 22 |
+
"messages": history + [prompt_msg]
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
response = requests.post(url, headers=headers, json=data)
|
| 26 |
+
json_data = json.loads(response.text)
|
| 27 |
+
|
| 28 |
+
response = json_data["choices"][0]["message"]
|
| 29 |
+
|
| 30 |
+
history.append(prompt_msg)
|
| 31 |
+
history.append(response)
|
| 32 |
+
|
| 33 |
+
return None, [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], history
|
| 34 |
+
|
| 35 |
+
css = """
|
| 36 |
+
#col-container {max-width: 50%; margin-left: auto; margin-right: auto;}
|
| 37 |
+
#chatbox {min-height: 400px;}
|
| 38 |
+
#header {text-align: center;}
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
with gr.Blocks(css=css) as demo:
|
| 42 |
+
history = gr.State([])
|
| 43 |
+
|
| 44 |
+
with gr.Column(elem_id="col-container"):
|
| 45 |
+
gr.Markdown("""## OpenAI Chatbot Demo
|
| 46 |
+
Using the ofiicial API and GPT-3.5 Turbo model""", elem_id="header")
|
| 47 |
+
chatbot = gr.Chatbot(elem_id="chatbox")
|
| 48 |
+
input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
|
| 49 |
+
|
| 50 |
+
input_message.submit(openai_chat, [input_message, history], [input_message, chatbot, history])
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
demo.launch()
|