Abs6187 commited on
Commit
feb6937
·
verified ·
1 Parent(s): 2293c14

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -49
app.py CHANGED
@@ -2,87 +2,79 @@ import os
2
  import gradio as gr
3
  import requests
4
 
5
- # -----------------------------
6
- # GPT5 Model Class
7
- # -----------------------------
8
  class GPT5Model:
9
- def __init__(self, api_key):
 
 
 
 
 
10
  self.api_key = api_key
11
  self.system_prompt = (
12
  "You are GPT-5, the most advanced AI model available. "
13
  "Answer accurately, intelligently, and helpfully."
14
  )
15
 
16
- def generate_response(self, prompt):
 
 
 
 
 
17
  headers = {
18
  "Authorization": f"Bearer {self.api_key}",
19
  "Content-Type": "application/json"
20
  }
21
  full_prompt = f"{self.system_prompt}\nUser: {prompt}\nGPT-5:"
22
- data = {
23
- "prompt": full_prompt,
24
- "max_tokens": 500
25
- }
26
 
27
  try:
28
- response = requests.post("https://api.pplx.ai/v1/generate", json=data, headers=headers, timeout=15)
 
 
 
 
29
  except requests.exceptions.RequestException as e:
30
- return f"Error: Could not reach API. {e}"
31
 
 
 
32
  if response.status_code != 200:
33
- return f"Error: API key exhausted or invalid. ({response.status_code})"
34
 
35
  try:
36
- result = response.json()
37
- choices = result.get("choices", [])
38
- if not choices or "text" not in choices[0] or not choices[0]["text"].strip():
39
- return "Error: API key exhausted or invalid."
40
- return choices[0]["text"].strip()
41
- except Exception:
42
- return "Error: API key exhausted or invalid."
43
 
44
- # -----------------------------
45
- # Load API key
46
- # -----------------------------
47
  api_key = os.getenv("PPLX_API_KEY")
48
  if not api_key:
49
- raise ValueError("API key not found. Please set PPLX_API_KEY environment variable.")
50
 
51
  model = GPT5Model(api_key)
52
 
53
- # -----------------------------
54
- # UI Function
55
- # -----------------------------
56
- def chat_with_gpt5(user_input):
57
- return model.generate_response(user_input)
58
 
59
- # -----------------------------
60
- # Build Better UI
61
- # -----------------------------
62
  with gr.Blocks(css="""
63
- #title {text-align: center; font-size: 28px; font-weight: bold;}
64
- #footer {text-align: center; font-size: 14px; color: gray;}
65
  """) as demo:
66
  gr.Markdown("<div id='title'>🚀 GPT-5 Model Interface</div>")
 
67
  with gr.Row():
68
- with gr.Column(scale=1):
69
- chatbot = gr.Chatbot(height=400, label="GPT-5 Conversation")
70
- with gr.Row():
71
- txt = gr.Textbox(
72
- show_label=False,
73
- placeholder="Type your message here...",
74
- container=False
75
- )
76
- send_btn = gr.Button("Send", variant="primary")
77
-
78
  gr.Markdown("<div id='footer'>Powered by GPT-5 API Simulation | © 2025</div>")
79
 
80
- # Handle chat logic
81
- def respond(message, chat_history):
82
- bot_reply = chat_with_gpt5(message)
83
- chat_history.append(("You: " + message, "GPT-5: " + bot_reply))
84
- return "", chat_history
85
-
86
  send_btn.click(respond, [txt, chatbot], [txt, chatbot])
87
  txt.submit(respond, [txt, chatbot], [txt, chatbot])
88
 
 
2
  import gradio as gr
3
  import requests
4
 
 
 
 
5
  class GPT5Model:
6
+ """
7
+ GPT5Model handles interactions with the GPT-5 API.
8
+ It includes system prompts, request construction, timeout handling,
9
+ and graceful error responses if the API can't be reached.
10
+ """
11
+ def __init__(self, api_key: str):
12
  self.api_key = api_key
13
  self.system_prompt = (
14
  "You are GPT-5, the most advanced AI model available. "
15
  "Answer accurately, intelligently, and helpfully."
16
  )
17
 
18
+ def generate_response(self, prompt: str) -> str:
19
+ """
20
+ Sends a prompt to the GPT-5 API and returns the response text.
21
+ If there's a connection error, timeout, or invalid API key, returns a friendly error message.
22
+ """
23
+ url = "https://api.pplx.ai/v1/generate"
24
  headers = {
25
  "Authorization": f"Bearer {self.api_key}",
26
  "Content-Type": "application/json"
27
  }
28
  full_prompt = f"{self.system_prompt}\nUser: {prompt}\nGPT-5:"
29
+ payload = {"prompt": full_prompt, "max_tokens": 500}
 
 
 
30
 
31
  try:
32
+ response = requests.post(url, json=payload, headers=headers, timeout=15)
33
+ except requests.exceptions.Timeout:
34
+ return "Error: Request timed out. Please check your network or try again later."
35
+ except requests.exceptions.ConnectionError:
36
+ return "Error: Could not reach API. Please check network settings."
37
  except requests.exceptions.RequestException as e:
38
+ return f"Error: Unexpected error occurred: {e}"
39
 
40
+ if response.status_code == 401:
41
+ return "Error: API key invalid or expired."
42
  if response.status_code != 200:
43
+ return f"Error: API returned status {response.status_code}."
44
 
45
  try:
46
+ data = response.json()
47
+ text = data.get("choices", [{}])[0].get("text", "").strip()
48
+ if not text:
49
+ return "Error: No response content. API key may be exhausted."
50
+ return text
51
+ except ValueError:
52
+ return "Error: Could not parse API response."
53
 
54
+ # === Load API Key ===
 
 
55
  api_key = os.getenv("PPLX_API_KEY")
56
  if not api_key:
57
+ raise EnvironmentError("API key not found. Please set PPLX_API_KEY environment variable.")
58
 
59
  model = GPT5Model(api_key)
60
 
61
+ def respond(message, chat_history):
62
+ reply = model.generate_response(message)
63
+ chat_history.append((message, reply))
64
+ return "", chat_history
 
65
 
66
+ # === Gradio UI ===
 
 
67
  with gr.Blocks(css="""
68
+ #title {text-align: center; font-size: 28px; font-weight: bold;}
69
+ #footer {text-align: center; font-size: 14px; color: gray;}
70
  """) as demo:
71
  gr.Markdown("<div id='title'>🚀 GPT-5 Model Interface</div>")
72
+ chatbot = gr.Chatbot(label="Conversation with GPT-5", height=400)
73
  with gr.Row():
74
+ txt = gr.Textbox(show_label=False, placeholder="Type your message here…", container=False)
75
+ send_btn = gr.Button("Send", variant="primary")
 
 
 
 
 
 
 
 
76
  gr.Markdown("<div id='footer'>Powered by GPT-5 API Simulation | © 2025</div>")
77
 
 
 
 
 
 
 
78
  send_btn.click(respond, [txt, chatbot], [txt, chatbot])
79
  txt.submit(respond, [txt, chatbot], [txt, chatbot])
80