Spaces:
Runtime error
Runtime error
# app.py | |
import os | |
import gradio as gr | |
import openai | |
# ─── CONFIG ──────────────────────────────────────────────────────────────────── | |
KEY_FILE = "openai_api_key.txt" | |
MODEL = "gpt-4o-2024-05-13" | |
# Try to load a cached key (global for all users) | |
if os.path.exists(KEY_FILE): | |
with open(KEY_FILE, "r") as f: | |
DEFAULT_KEY = f.read().strip() | |
else: | |
DEFAULT_KEY = "" | |
# ─── HELPERS ─────────────────────────────────────────────────────────────────── | |
def save_api_key(api_key: str) -> str: | |
"""Save the key to disk so it's remembered for all future sessions.""" | |
with open(KEY_FILE, "w") as f: | |
f.write(api_key.strip()) | |
return "✅ API key saved and will be used for all users." | |
def chat_with_openai(api_key: str, user_message: str, history: list) -> list: | |
"""Invoke GPT-4o with the supplied API key and append to chat history.""" | |
openai.api_key = api_key.strip() | |
# ensure history is a list of tuples [(user, bot), ...] | |
history = history or [] | |
# Build messages in OpenAI format | |
messages = [] | |
for u, a in history: | |
messages.append({"role":"user", "content": u}) | |
messages.append({"role":"assistant","content": a}) | |
messages.append({"role":"user", "content": user_message}) | |
# Call the API | |
resp = openai.ChatCompletion.create( | |
model=MODEL, | |
messages=messages, | |
) | |
answer = resp.choices[0].message.content | |
history.append((user_message, answer)) | |
return history | |
# ─── UI LAYOUT ──────────────────────────────────────────────────────────────── | |
with gr.Blocks(title="🌐 GPT-4o Multimodal (Skeleton)") as demo: | |
gr.Markdown( | |
""" | |
# 🤖 GPT-4o Client | |
Enter your OpenAI API key once below. | |
It will be cached on the server for all future sessions. | |
""" | |
) | |
with gr.Row(): | |
api_key_input = gr.Textbox( | |
label="🔑 OpenAI API Key", | |
placeholder="sk-…", | |
value=DEFAULT_KEY, | |
type="password", | |
) | |
save_button = gr.Button("💾 Save API Key") | |
save_status = gr.Textbox( | |
label="Status", | |
interactive=False, | |
placeholder="–" | |
) | |
# Wire the save button | |
save_button.click( | |
fn=save_api_key, | |
inputs=api_key_input, | |
outputs=save_status, | |
) | |
gr.Markdown("--- | |
## 💬 Chat with GPT-4o") | |
chatbot = gr.Chatbot(label="Chat History") | |
msg = gr.Textbox( | |
label="Your message", | |
placeholder="Type something and press Enter…", | |
) | |
# When you hit Enter in the textbox, call the chat fn | |
msg.submit( | |
fn=chat_with_openai, | |
inputs=[api_key_input, msg, chatbot], | |
outputs=chatbot, | |
) | |
# ─── RUN ─────────────────────────────────────────────────────────────────────── | |
if __name__ == "__main__": | |
# Use 0.0.0.0 if you want external access; port can be adjusted as needed | |
demo.launch(server_name="0.0.0.0", server_port=7860) | |