Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,11 +6,53 @@ from openai import OpenAI
|
|
| 6 |
# Load OpenAI key from HF Secrets
|
| 7 |
# -----------------------------
|
| 8 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 10 |
|
| 11 |
-
SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
|
|
|
|
|
|
|
|
|
|
| 14 |
def init_messages():
|
| 15 |
return [
|
| 16 |
{
|
|
@@ -19,15 +61,32 @@ def init_messages():
|
|
| 19 |
}
|
| 20 |
]
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def respond(user_text, chat_history, messages):
|
| 23 |
if messages is None:
|
| 24 |
messages = init_messages()
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
| 30 |
|
|
|
|
| 31 |
response = client.responses.create(
|
| 32 |
model="gpt-5-chat-latest",
|
| 33 |
input=messages,
|
|
@@ -42,18 +101,22 @@ def respond(user_text, chat_history, messages):
|
|
| 42 |
|
| 43 |
assistant_text = response.output_text
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
|
|
|
|
| 51 |
|
| 52 |
return "", chat_history, messages
|
| 53 |
|
| 54 |
|
| 55 |
# -----------------------------
|
| 56 |
-
#
|
| 57 |
# -----------------------------
|
| 58 |
FAQ_QUESTIONS = [
|
| 59 |
"What is the difference between a list, tuple, and set in Python?",
|
|
@@ -75,21 +138,38 @@ LOGO_URL = "https://raw.githubusercontent.com/Decoding-Data-Science/nov25/main/l
|
|
| 75 |
|
| 76 |
css = """
|
| 77 |
#app_container {max-width: 1200px; margin: 0 auto;}
|
| 78 |
-
|
| 79 |
-
.header-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
.
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
}
|
| 88 |
-
"""
|
| 89 |
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
|
|
|
|
| 93 |
with gr.Row():
|
| 94 |
with gr.Column(scale=1, min_width=80):
|
| 95 |
gr.Image(
|
|
@@ -100,36 +180,37 @@ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo
|
|
| 100 |
width=64,
|
| 101 |
container=False
|
| 102 |
)
|
| 103 |
-
|
| 104 |
with gr.Column(scale=10):
|
| 105 |
-
gr.HTML(
|
| 106 |
-
|
| 107 |
-
<div>
|
| 108 |
-
<div
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
| 111 |
</div>
|
| 112 |
</div>
|
| 113 |
-
|
| 114 |
-
|
| 115 |
|
| 116 |
gr.Markdown("---")
|
| 117 |
|
| 118 |
-
# State
|
| 119 |
state = gr.State(init_messages())
|
| 120 |
|
|
|
|
| 121 |
with gr.Row(equal_height=True):
|
| 122 |
-
|
| 123 |
-
# LEFT SIDE — FAQ
|
| 124 |
with gr.Column(scale=4, min_width=320):
|
| 125 |
with gr.Group(elem_classes=["faq-box"]):
|
| 126 |
gr.Markdown("### FAQ — Most Asked Python Questions")
|
| 127 |
-
gr.Markdown("Click a question to auto-fill it.")
|
| 128 |
|
| 129 |
faq_buttons = []
|
| 130 |
for q in FAQ_QUESTIONS:
|
| 131 |
-
|
| 132 |
-
faq_buttons.append(
|
| 133 |
|
| 134 |
gr.Markdown("### Quick prompt ideas")
|
| 135 |
quick = gr.Radio(
|
|
@@ -144,12 +225,13 @@ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo
|
|
| 144 |
value=None
|
| 145 |
)
|
| 146 |
|
| 147 |
-
# RIGHT
|
| 148 |
with gr.Column(scale=8, min_width=520):
|
| 149 |
-
|
| 150 |
chatbot = gr.Chatbot(
|
| 151 |
height=520,
|
| 152 |
label="Conversation"
|
|
|
|
|
|
|
| 153 |
)
|
| 154 |
|
| 155 |
with gr.Row():
|
|
@@ -163,31 +245,32 @@ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo
|
|
| 163 |
with gr.Row():
|
| 164 |
clear = gr.Button("Clear Chat")
|
| 165 |
gr.Markdown(
|
| 166 |
-
"<span style='opacity:0.7;font-size:12px;'>Context is preserved unless
|
| 167 |
)
|
| 168 |
|
| 169 |
-
# FAQ
|
| 170 |
for b, q in zip(faq_buttons, FAQ_QUESTIONS):
|
| 171 |
-
b.click(lambda q=q: set_question(q), None, msg)
|
| 172 |
|
| 173 |
-
#
|
| 174 |
-
def
|
| 175 |
if not pref:
|
| 176 |
return current_text
|
| 177 |
if current_text and current_text.strip():
|
| 178 |
return f"{current_text.strip()} ({pref})"
|
| 179 |
return pref
|
| 180 |
|
| 181 |
-
quick.change(
|
| 182 |
|
| 183 |
-
#
|
| 184 |
-
msg.submit(respond, [msg, chatbot, state], [msg, chatbot, state])
|
| 185 |
-
send.click(respond, [msg, chatbot, state], [msg, chatbot, state])
|
| 186 |
|
| 187 |
-
# Clear
|
| 188 |
-
clear.click(clear_all, None, [chatbot, state, msg])
|
| 189 |
|
| 190 |
-
# Launch with theme + css (Gradio 6 requirement)
|
| 191 |
demo.launch(
|
| 192 |
-
debug=False
|
| 193 |
-
)
|
|
|
|
|
|
|
|
|
| 6 |
# Load OpenAI key from HF Secrets
|
| 7 |
# -----------------------------
|
| 8 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 9 |
+
|
| 10 |
+
if not OPENAI_API_KEY:
|
| 11 |
+
raise ValueError(
|
| 12 |
+
"OPENAI_API_KEY is not set. "
|
| 13 |
+
"Add it in your Hugging Face Space: Settings → Variables and secrets → Secrets."
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 17 |
|
| 18 |
+
SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
|
| 19 |
+
|
| 20 |
+
Requirements:
|
| 21 |
+
- Maintain conversational context over multiple user turns.
|
| 22 |
+
- Respond helpfully and accurately to a wide range of user inputs.
|
| 23 |
+
- Reason about user intent before generating each response.
|
| 24 |
+
- Politely ask clarifying questions if a request is ambiguous or unclear.
|
| 25 |
+
- Avoid hallucination or speculation—respond only with information you can justify or infer from context.
|
| 26 |
+
- If unable to answer, politely acknowledge the limitation.
|
| 27 |
+
|
| 28 |
+
Process:
|
| 29 |
+
1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
|
| 30 |
+
2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
|
| 31 |
+
3. If more information is needed, ask targeted clarifying questions.
|
| 32 |
+
4. Output your response, maintaining natural tone and conversational flow.
|
| 33 |
+
5. Continue the conversation until the user indicates they are finished.
|
| 34 |
+
|
| 35 |
+
Output:
|
| 36 |
+
- Each response should be in plain English, no markdown or code blocks unless explicitly requested.
|
| 37 |
+
- Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
|
| 38 |
+
|
| 39 |
+
Example—Instructions:
|
| 40 |
+
- Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
|
| 41 |
+
- Conclusion/Output: "Sure! In Python, a list is a collection of items in a particular order. For example: my_list = [1, 2, 3, 4]. Would you like to see how to add or remove items?"
|
| 42 |
+
|
| 43 |
+
(For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
|
| 44 |
+
|
| 45 |
+
Edge Cases & Important Considerations:
|
| 46 |
+
- If the user refers to prior conversation context, recall and incorporate it.
|
| 47 |
+
- Be warm, engaging, and never condescending.
|
| 48 |
+
- If asked for code, provide only what is needed and explain concisely.
|
| 49 |
+
|
| 50 |
+
REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
|
| 51 |
"""
|
| 52 |
|
| 53 |
+
# -----------------------------
|
| 54 |
+
# OpenAI message state (internal)
|
| 55 |
+
# -----------------------------
|
| 56 |
def init_messages():
|
| 57 |
return [
|
| 58 |
{
|
|
|
|
| 61 |
}
|
| 62 |
]
|
| 63 |
|
| 64 |
+
# -----------------------------
|
| 65 |
+
# Gradio Chatbot UI history (messages format)
|
| 66 |
+
# Each item must be: {"role": "...", "content": "..."}
|
| 67 |
+
# -----------------------------
|
| 68 |
+
def append_ui_history(chat_history, user_text, assistant_text):
|
| 69 |
+
if chat_history is None:
|
| 70 |
+
chat_history = []
|
| 71 |
+
chat_history = chat_history + [
|
| 72 |
+
{"role": "user", "content": user_text},
|
| 73 |
+
{"role": "assistant", "content": assistant_text},
|
| 74 |
+
]
|
| 75 |
+
return chat_history
|
| 76 |
+
|
| 77 |
def respond(user_text, chat_history, messages):
|
| 78 |
if messages is None:
|
| 79 |
messages = init_messages()
|
| 80 |
|
| 81 |
+
# add user turn for OpenAI
|
| 82 |
+
messages.append(
|
| 83 |
+
{
|
| 84 |
+
"role": "user",
|
| 85 |
+
"content": [{"type": "input_text", "text": user_text}]
|
| 86 |
+
}
|
| 87 |
+
)
|
| 88 |
|
| 89 |
+
# call API
|
| 90 |
response = client.responses.create(
|
| 91 |
model="gpt-5-chat-latest",
|
| 92 |
input=messages,
|
|
|
|
| 101 |
|
| 102 |
assistant_text = response.output_text
|
| 103 |
|
| 104 |
+
# add assistant turn for OpenAI
|
| 105 |
+
messages.append(
|
| 106 |
+
{
|
| 107 |
+
"role": "assistant",
|
| 108 |
+
"content": [{"type": "output_text", "text": assistant_text}]
|
| 109 |
+
}
|
| 110 |
+
)
|
| 111 |
|
| 112 |
+
# update UI history (messages format)
|
| 113 |
+
chat_history = append_ui_history(chat_history, user_text, assistant_text)
|
| 114 |
|
| 115 |
return "", chat_history, messages
|
| 116 |
|
| 117 |
|
| 118 |
# -----------------------------
|
| 119 |
+
# Gradio UI
|
| 120 |
# -----------------------------
|
| 121 |
FAQ_QUESTIONS = [
|
| 122 |
"What is the difference between a list, tuple, and set in Python?",
|
|
|
|
| 138 |
|
| 139 |
css = """
|
| 140 |
#app_container {max-width: 1200px; margin: 0 auto;}
|
| 141 |
+
|
| 142 |
+
.header-wrap {
|
| 143 |
+
display: flex;
|
| 144 |
+
align-items: center;
|
| 145 |
+
gap: 14px;
|
| 146 |
+
padding: 10px 6px 2px 6px;
|
| 147 |
+
}
|
| 148 |
+
.header-title {
|
| 149 |
+
font-size: 28px;
|
| 150 |
+
font-weight: 700;
|
| 151 |
+
line-height: 1.1;
|
| 152 |
+
}
|
| 153 |
+
.header-subtitle {
|
| 154 |
+
font-size: 12.5px;
|
| 155 |
+
opacity: 0.75;
|
| 156 |
+
margin-top: 2px;
|
| 157 |
}
|
|
|
|
| 158 |
|
| 159 |
+
.faq-box {
|
| 160 |
+
border: 1px solid rgba(255,255,255,0.08);
|
| 161 |
+
border-radius: 12px;
|
| 162 |
+
padding: 14px;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
.faq-btn button {
|
| 166 |
+
width: 100%;
|
| 167 |
+
justify-content: flex-start;
|
| 168 |
+
}
|
| 169 |
+
"""
|
| 170 |
|
| 171 |
+
with gr.Blocks(elem_id="app_container") as demo:
|
| 172 |
+
# Header Row
|
| 173 |
with gr.Row():
|
| 174 |
with gr.Column(scale=1, min_width=80):
|
| 175 |
gr.Image(
|
|
|
|
| 180 |
width=64,
|
| 181 |
container=False
|
| 182 |
)
|
|
|
|
| 183 |
with gr.Column(scale=10):
|
| 184 |
+
gr.HTML(
|
| 185 |
+
"""
|
| 186 |
+
<div class="header-wrap">
|
| 187 |
+
<div>
|
| 188 |
+
<div class="header-title">Python Tutor Bot</div>
|
| 189 |
+
<div class="header-subtitle">
|
| 190 |
+
Ask anything about Python — concepts, debugging, best practices, and examples.
|
| 191 |
+
</div>
|
| 192 |
</div>
|
| 193 |
</div>
|
| 194 |
+
"""
|
| 195 |
+
)
|
| 196 |
|
| 197 |
gr.Markdown("---")
|
| 198 |
|
| 199 |
+
# State for OpenAI messages
|
| 200 |
state = gr.State(init_messages())
|
| 201 |
|
| 202 |
+
# Two-column layout
|
| 203 |
with gr.Row(equal_height=True):
|
| 204 |
+
# LEFT: FAQ + Quick Ask
|
|
|
|
| 205 |
with gr.Column(scale=4, min_width=320):
|
| 206 |
with gr.Group(elem_classes=["faq-box"]):
|
| 207 |
gr.Markdown("### FAQ — Most Asked Python Questions")
|
| 208 |
+
gr.Markdown("Click a question to auto-fill it, then press **Enter** or click **Send**.")
|
| 209 |
|
| 210 |
faq_buttons = []
|
| 211 |
for q in FAQ_QUESTIONS:
|
| 212 |
+
b = gr.Button(q, elem_classes=["faq-btn"])
|
| 213 |
+
faq_buttons.append(b)
|
| 214 |
|
| 215 |
gr.Markdown("### Quick prompt ideas")
|
| 216 |
quick = gr.Radio(
|
|
|
|
| 225 |
value=None
|
| 226 |
)
|
| 227 |
|
| 228 |
+
# RIGHT: Chat area
|
| 229 |
with gr.Column(scale=8, min_width=520):
|
|
|
|
| 230 |
chatbot = gr.Chatbot(
|
| 231 |
height=520,
|
| 232 |
label="Conversation"
|
| 233 |
+
# No bubble_full_width
|
| 234 |
+
# No type=
|
| 235 |
)
|
| 236 |
|
| 237 |
with gr.Row():
|
|
|
|
| 245 |
with gr.Row():
|
| 246 |
clear = gr.Button("Clear Chat")
|
| 247 |
gr.Markdown(
|
| 248 |
+
"<span style='opacity:0.7;font-size:12px;'>Context is preserved across turns unless you clear.</span>"
|
| 249 |
)
|
| 250 |
|
| 251 |
+
# FAQ -> fill textbox
|
| 252 |
for b, q in zip(faq_buttons, FAQ_QUESTIONS):
|
| 253 |
+
b.click(fn=lambda q=q: set_question(q), inputs=None, outputs=msg)
|
| 254 |
|
| 255 |
+
# Optional quick preference: append hint to textbox (UI-only)
|
| 256 |
+
def apply_quick_pref(pref, current_text):
|
| 257 |
if not pref:
|
| 258 |
return current_text
|
| 259 |
if current_text and current_text.strip():
|
| 260 |
return f"{current_text.strip()} ({pref})"
|
| 261 |
return pref
|
| 262 |
|
| 263 |
+
quick.change(fn=apply_quick_pref, inputs=[quick, msg], outputs=msg)
|
| 264 |
|
| 265 |
+
# Submit logic
|
| 266 |
+
msg.submit(respond, inputs=[msg, chatbot, state], outputs=[msg, chatbot, state])
|
| 267 |
+
send.click(respond, inputs=[msg, chatbot, state], outputs=[msg, chatbot, state])
|
| 268 |
|
| 269 |
+
# Clear
|
| 270 |
+
clear.click(fn=clear_all, inputs=None, outputs=[chatbot, state, msg])
|
| 271 |
|
|
|
|
| 272 |
demo.launch(
|
| 273 |
+
debug=False,
|
| 274 |
+
theme=gr.themes.Soft(),
|
| 275 |
+
css=css
|
| 276 |
+
)
|