GPT5_Demo / app.py
Abs6187's picture
Update app.py
feb6937 verified
raw
history blame
3.18 kB
import os
import gradio as gr
import requests
class GPT5Model:
"""
GPT5Model handles interactions with the GPT-5 API.
It includes system prompts, request construction, timeout handling,
and graceful error responses if the API can't be reached.
"""
def __init__(self, api_key: str):
self.api_key = api_key
self.system_prompt = (
"You are GPT-5, the most advanced AI model available. "
"Answer accurately, intelligently, and helpfully."
)
def generate_response(self, prompt: str) -> str:
"""
Sends a prompt to the GPT-5 API and returns the response text.
If there's a connection error, timeout, or invalid API key, returns a friendly error message.
"""
url = "https://api.pplx.ai/v1/generate"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
full_prompt = f"{self.system_prompt}\nUser: {prompt}\nGPT-5:"
payload = {"prompt": full_prompt, "max_tokens": 500}
try:
response = requests.post(url, json=payload, headers=headers, timeout=15)
except requests.exceptions.Timeout:
return "Error: Request timed out. Please check your network or try again later."
except requests.exceptions.ConnectionError:
return "Error: Could not reach API. Please check network settings."
except requests.exceptions.RequestException as e:
return f"Error: Unexpected error occurred: {e}"
if response.status_code == 401:
return "Error: API key invalid or expired."
if response.status_code != 200:
return f"Error: API returned status {response.status_code}."
try:
data = response.json()
text = data.get("choices", [{}])[0].get("text", "").strip()
if not text:
return "Error: No response content. API key may be exhausted."
return text
except ValueError:
return "Error: Could not parse API response."
# === Load API Key ===
api_key = os.getenv("PPLX_API_KEY")
if not api_key:
raise EnvironmentError("API key not found. Please set PPLX_API_KEY environment variable.")
model = GPT5Model(api_key)
def respond(message, chat_history):
reply = model.generate_response(message)
chat_history.append((message, reply))
return "", chat_history
# === Gradio UI ===
with gr.Blocks(css="""
#title {text-align: center; font-size: 28px; font-weight: bold;}
#footer {text-align: center; font-size: 14px; color: gray;}
""") as demo:
gr.Markdown("<div id='title'>🚀 GPT-5 Model Interface</div>")
chatbot = gr.Chatbot(label="Conversation with GPT-5", height=400)
with gr.Row():
txt = gr.Textbox(show_label=False, placeholder="Type your message here…", container=False)
send_btn = gr.Button("Send", variant="primary")
gr.Markdown("<div id='footer'>Powered by GPT-5 API Simulation | © 2025</div>")
send_btn.click(respond, [txt, chatbot], [txt, chatbot])
txt.submit(respond, [txt, chatbot], [txt, chatbot])
demo.launch()