Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,29 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 21 |
-
response =
|
| 22 |
model="gpt-3.5-turbo", # Or another model like "gpt-4"
|
| 23 |
messages=messages,
|
| 24 |
max_tokens=150,
|
|
@@ -36,7 +41,7 @@ def chat_with_gpt(message, history):
|
|
| 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",
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from openai 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 |
+
# Initialize the OpenAI client
|
| 12 |
+
# The API key is now passed directly to the client
|
| 13 |
+
client = OpenAI(api_key=openai_api_key)
|
| 14 |
|
| 15 |
# Define the function that interacts with the ChatGPT API
|
| 16 |
def chat_with_gpt(message, history):
|
| 17 |
# Prepare the messages for the API call
|
| 18 |
messages = []
|
| 19 |
+
# Use the new format for the chatbot history
|
| 20 |
for human, assistant in history:
|
| 21 |
messages.append({"role": "user", "content": human})
|
| 22 |
messages.append({"role": "assistant", "content": assistant})
|
| 23 |
messages.append({"role": "user", "content": message})
|
| 24 |
|
| 25 |
+
# Make the API call using the client object
|
| 26 |
+
response = client.chat.completions.create(
|
| 27 |
model="gpt-3.5-turbo", # Or another model like "gpt-4"
|
| 28 |
messages=messages,
|
| 29 |
max_tokens=150,
|
|
|
|
| 41 |
# Create the Gradio interface
|
| 42 |
demo = gr.ChatInterface(
|
| 43 |
fn=chat_with_gpt,
|
| 44 |
+
chatbot=gr.Chatbot(height=500, type="messages"), # Add type="messages" to match the new API
|
| 45 |
textbox=gr.Textbox(placeholder="Ask me a question...", container=False, scale=7),
|
| 46 |
title="ChatGPT API Chatbot",
|
| 47 |
theme="soft",
|