aasteven commited on
Commit
dd87744
·
verified ·
1 Parent(s): 1e728b5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import os
4
+ import json
5
+
6
+ # Load the API key from a JSON file for security
7
+ with open("config.json") as config_file:
8
+ config = json.load(config_file)
9
+ openai.api_key = config.get("OPENAI_API_KEY")
10
+
11
+ # Define the function that interacts with the ChatGPT API
12
+ def chat_with_gpt(message, history):
13
+ # Prepare the messages for the API call
14
+ messages = []
15
+ for human, assistant in history:
16
+ messages.append({"role": "user", "content": human})
17
+ messages.append({"role": "assistant", "content": assistant})
18
+ messages.append({"role": "user", "content": message})
19
+
20
+ # Make the API call to OpenAI
21
+ response = openai.ChatCompletion.create(
22
+ model="gpt-3.5-turbo", # Or another model like "gpt-4"
23
+ messages=messages,
24
+ max_tokens=150,
25
+ temperature=0.7,
26
+ stream=True # Enable streaming for a better user experience
27
+ )
28
+
29
+ # Stream the response back to Gradio
30
+ full_response = ""
31
+ for chunk in response:
32
+ content = chunk.choices[0].delta.get("content", "")
33
+ full_response += content
34
+ yield full_response
35
+
36
+ # Create the Gradio interface
37
+ demo = gr.ChatInterface(
38
+ fn=chat_with_gpt,
39
+ chatbot=gr.Chatbot(height=500),
40
+ textbox=gr.Textbox(placeholder="Ask me a question...", container=False, scale=7),
41
+ title="ChatGPT API Chatbot",
42
+ theme="soft",
43
+ examples=["What is a large language model?", "Tell me a joke.", "Write a short Python function."],
44
+ cache_examples=False,
45
+ undo_btn="Delete Previous",
46
+ clear_btn="Clear",
47
+ )
48
+
49
+ # Launch the Gradio app
50
+ demo.launch()