eaglelandsonce commited on
Commit
03436df
·
verified ·
1 Parent(s): 174cb4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -46
app.py CHANGED
@@ -1,73 +1,57 @@
1
- import os
2
  import gradio as gr
3
  from openai import OpenAI
4
 
5
- # --- Configuration ---
6
- # Read from environment for safety. Set OPENAI_API_KEY before running.
7
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
8
- if not OPENAI_API_KEY:
9
- raise RuntimeError(
10
- "Missing OPENAI_API_KEY. Set it in your environment: "
11
- "export OPENAI_API_KEY='sk-...' (Linux/Mac) or "
12
- "setx OPENAI_API_KEY \"sk-...\" (Windows)"
13
- )
14
-
15
- # Optional: override base URL if you use a proxy/self-hosted gateway.
16
- # For the standard OpenAI endpoint you can omit base_url entirely.
17
- client = OpenAI(
18
- api_key=OPENAI_API_KEY,
19
- base_url=os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
20
- )
21
-
22
- # Default system prompt and model; adjust as desired.
23
  DEFAULT_SYSTEM_PROMPT = "You are a helpful, concise assistant."
24
- DEFAULT_MODEL = os.getenv("OPENAI_MODEL", "gpt-5-chat-latest") # use a current chat model
25
 
26
- def chat_fn(message, history, system_prompt, temperature, max_tokens):
27
  """
28
- Gradio ChatInterface passes:
29
- - message: current user message (str)
30
- - history: list[tuple[str,str]] of (user, assistant) turns
31
- We convert to OpenAI's chat message format and call the Chat Completions API.
32
  """
33
- # Build messages: system + alternating user/assistant + latest user
34
- messages = [{"role": "system", "content": system_prompt.strip() or DEFAULT_SYSTEM_PROMPT}]
35
 
 
 
 
 
36
  for user_msg, assistant_msg in history:
37
  if user_msg:
38
  messages.append({"role": "user", "content": user_msg})
39
  if assistant_msg:
40
  messages.append({"role": "assistant", "content": assistant_msg})
41
-
42
  messages.append({"role": "user", "content": message})
43
 
44
- resp = client.chat.completions.create(
45
- model=DEFAULT_MODEL,
46
- messages=messages,
47
- temperature=temperature,
48
- max_tokens=max_tokens if max_tokens and max_tokens > 0 else None,
49
- )
50
-
51
- reply = resp.choices[0].message.content
52
- return reply
 
53
 
54
  with gr.Blocks(title="OpenAI Chat (Gradio)") as demo:
55
- gr.Markdown("## OpenAI Chatbot\nEnter a message below to chat.")
56
 
57
  with gr.Row():
58
- system_prompt = gr.Textbox(
59
- label="System prompt",
60
- value=DEFAULT_SYSTEM_PROMPT,
61
- lines=2
62
- )
63
 
64
  with gr.Row():
65
  temperature = gr.Slider(0.0, 2.0, value=0.7, step=0.1, label="Temperature")
66
  max_tokens = gr.Slider(64, 4096, value=512, step=32, label="Max tokens (response)")
67
 
68
  chat = gr.ChatInterface(
69
- fn=lambda msg, hist: chat_fn(msg, hist, system_prompt.value, temperature.value, int(max_tokens.value)),
70
- type="messages", # keeps history as list of tuples
 
 
71
  title="OpenAI Chatbot",
72
  retry_btn="Retry",
73
  undo_btn="Remove last",
@@ -76,5 +60,4 @@ with gr.Blocks(title="OpenAI Chat (Gradio)") as demo:
76
  )
77
 
78
  if __name__ == "__main__":
79
- # You can set server_name="0.0.0.0" if deploying in a container.
80
  demo.launch()
 
 
1
  import gradio as gr
2
  from openai import OpenAI
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  DEFAULT_SYSTEM_PROMPT = "You are a helpful, concise assistant."
5
+ DEFAULT_MODEL = "gpt-5-chat-latest"
6
 
7
+ def chat_fn(message, history, system_prompt, temperature, max_tokens, api_key, base_url):
8
  """
9
+ Main chat function. Uses the API key typed into the interface.
 
 
 
10
  """
11
+ if not api_key:
12
+ return "⚠️ Please provide an OpenAI API key in the input box above."
13
 
14
+ client = OpenAI(api_key=api_key, base_url=base_url or "https://api.openai.com/v1")
15
+
16
+ # Build messages for chat completion
17
+ messages = [{"role": "system", "content": system_prompt.strip() or DEFAULT_SYSTEM_PROMPT}]
18
  for user_msg, assistant_msg in history:
19
  if user_msg:
20
  messages.append({"role": "user", "content": user_msg})
21
  if assistant_msg:
22
  messages.append({"role": "assistant", "content": assistant_msg})
 
23
  messages.append({"role": "user", "content": message})
24
 
25
+ try:
26
+ resp = client.chat.completions.create(
27
+ model=DEFAULT_MODEL,
28
+ messages=messages,
29
+ temperature=temperature,
30
+ max_tokens=max_tokens if max_tokens and max_tokens > 0 else None,
31
+ )
32
+ return resp.choices[0].message.content
33
+ except Exception as e:
34
+ return f"❌ Error: {str(e)}"
35
 
36
  with gr.Blocks(title="OpenAI Chat (Gradio)") as demo:
37
+ gr.Markdown("## 🔑 OpenAI Chatbot\nEnter your API key and start chatting.")
38
 
39
  with gr.Row():
40
+ api_key = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...", lines=1)
41
+ base_url = gr.Textbox(label="Base URL", value="https://api.openai.com/v1", lines=1)
42
+
43
+ with gr.Row():
44
+ system_prompt = gr.Textbox(label="System prompt", value=DEFAULT_SYSTEM_PROMPT, lines=2)
45
 
46
  with gr.Row():
47
  temperature = gr.Slider(0.0, 2.0, value=0.7, step=0.1, label="Temperature")
48
  max_tokens = gr.Slider(64, 4096, value=512, step=32, label="Max tokens (response)")
49
 
50
  chat = gr.ChatInterface(
51
+ fn=lambda msg, hist: chat_fn(msg, hist, system_prompt.value,
52
+ temperature.value, int(max_tokens.value),
53
+ api_key.value, base_url.value),
54
+ type="messages",
55
  title="OpenAI Chatbot",
56
  retry_btn="Retry",
57
  undo_btn="Remove last",
 
60
  )
61
 
62
  if __name__ == "__main__":
 
63
  demo.launch()