ChatGPT / chat_ui.py
niks1419's picture
Create chat_ui.py
98b884c verified
import gradio as gr
from openai import OpenAI
import os
# πŸ” Enter your API key (or set it as environment variable)
os.environ["OPENAI_API_KEY"] = "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"
client = OpenAI()
# --- Chat history ---
history = []
# --- Function to send user input to OpenAI API ---
def chat_with_gpt(message, history_list):
history_list = history_list or []
# Construct messages for the model
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for human, bot in history_list:
messages.append({"role": "user", "content": human})
messages.append({"role": "assistant", "content": bot})
messages.append({"role": "user", "content": message})
# Call the API
response = client.chat.completions.create(
model="gpt-4o-mini", # you can use gpt-4o, gpt-3.5-turbo, etc.
messages=messages,
temperature=0.7
)
reply = response.choices[0].message.content
history_list.append((message, reply))
return history_list, history_list
# --- Gradio Chat Interface ---
with gr.Blocks(title="ChatGPT via OpenAI API") as demo:
gr.Markdown("### πŸ€– ChatGPT (API-Powered) β€” No Pro Needed")
chatbot = gr.Chatbot(height=400)
msg = gr.Textbox(label="Your Message")
clear = gr.Button("Clear Chat")
msg.submit(chat_with_gpt, [msg, chatbot], [chatbot, chatbot])
clear.click(lambda: None, None, chatbot)
demo.launch()