raheeelarif86 commited on
Commit
50f4ae1
·
verified ·
1 Parent(s): 3942ebc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1534 -0
app.py ADDED
@@ -0,0 +1,1534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Open In Colab
3
+
4
+ pip install openai
5
+
6
+
7
+ Requirement already satisfied: openai in /usr/local/lib/python3.12/dist-packages (2.9.0)
8
+ Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.12/dist-packages (from openai) (4.12.0)
9
+ Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.12/dist-packages (from openai) (1.9.0)
10
+ Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from openai) (0.28.1)
11
+ Requirement already satisfied: jiter<1,>=0.10.0 in /usr/local/lib/python3.12/dist-packages (from openai) (0.12.0)
12
+ Requirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.12/dist-packages (from openai) (2.12.3)
13
+ Requirement already satisfied: sniffio in /usr/local/lib/python3.12/dist-packages (from openai) (1.3.1)
14
+ Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.12/dist-packages (from openai) (4.67.1)
15
+ Requirement already satisfied: typing-extensions<5,>=4.11 in /usr/local/lib/python3.12/dist-packages (from openai) (4.15.0)
16
+ Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.12/dist-packages (from anyio<5,>=3.5.0->openai) (3.11)
17
+ Requirement already satisfied: certifi in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->openai) (2025.11.12)
18
+ Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->openai) (1.0.9)
19
+ Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)
20
+ Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.12/dist-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)
21
+ Requirement already satisfied: pydantic-core==2.41.4 in /usr/local/lib/python3.12/dist-packages (from pydantic<3,>=1.9.0->openai) (2.41.4)
22
+ Requirement already satisfied: typing-inspection>=0.4.2 in /usr/local/lib/python3.12/dist-packages (from pydantic<3,>=1.9.0->openai) (0.4.2)
23
+
24
+ from google.colab import userdata
25
+ import os
26
+
27
+ os.environ["OPENAI_API_KEY"] = userdata.get("openai")
28
+
29
+
30
+
31
+ from openai import OpenAI
32
+
33
+ client = OpenAI()
34
+ #your system prompt -playground
35
+ SYSTEM_PROMPT = """
36
+
37
+ Use this system prompt to ensure the language model generates and interprets content strictly in Python.
38
+
39
+ ---
40
+
41
+ You are an AI that must interact exclusively using Python code.
42
+ - Respond ONLY with valid Python code to all prompts.
43
+ - Do not include any explanations, comments, or markdown formatting, unless explicitly requested.
44
+ - If a prompt cannot be fulfilled in Python or requests another language, respond with a single line: `Error: Python only.`
45
+ - Persist until you have fully completed the user's objective using ONLY Python.
46
+
47
+ **Output Format:**
48
+ - Plain text Python code (no markdown, explanations, or prose).
49
+ - If requested for structured output (e.g., JSON), generate via Python constructs only.
50
+
51
+ **Example Input and Output:**
52
+ Example 1
53
+ Input: "Create a function that adds two numbers."
54
+ Output:
55
+ def add(a, b):
56
+ return a + b
57
+
58
+ Example 2
59
+ Input: "Write C++ code for sorting."
60
+ Output:
61
+ Error: Python only.
62
+
63
+ ---
64
+
65
+ **Important:**
66
+ Always use pure Python. Explanations or other languages are not allowed. Respond strictly as outlined above.
67
+ """
68
+
69
+ messages = [
70
+ {
71
+ "role": "system",
72
+ "content": [
73
+ {"type": "input_text", "text": SYSTEM_PROMPT}
74
+ ],
75
+ }
76
+ ]
77
+
78
+ print("Chatbot ready. Type 'exit' to stop.")
79
+
80
+ while True:
81
+ user_text = input("You: ").strip()
82
+ if not user_text:
83
+ continue
84
+ if user_text.lower() in {"exit", "quit", "bye"}:
85
+ print("Bot: Goodbye!")
86
+ break
87
+
88
+ # Add user message
89
+ messages.append(
90
+ {
91
+ "role": "user",
92
+ "content": [
93
+ {"type": "input_text", "text": user_text}
94
+ ],
95
+ }
96
+ )
97
+
98
+ # Call the Responses API
99
+ response = client.responses.create(
100
+ model="gpt-5-chat-latest",
101
+ input=messages,
102
+ text={"format": {"type": "text"}},
103
+ reasoning={},
104
+ tools=[],
105
+ temperature=1,
106
+ max_output_tokens=2048,
107
+ top_p=1,
108
+ store=True,
109
+ include=["web_search_call.action.sources"]
110
+ )
111
+
112
+ assistant_text = response.output_text
113
+
114
+ print("Bot:", assistant_text)
115
+
116
+ # Store assistant message to preserve context
117
+ messages.append(
118
+ {
119
+ "role": "assistant",
120
+ "content": [
121
+ {"type": "output_text", "text": assistant_text}
122
+ ],
123
+ }
124
+ )
125
+
126
+
127
+ Chatbot ready. Type 'exit' to stop.
128
+ You: lahore
129
+ Bot: Error: Python only.
130
+ You: exit
131
+ Bot: Goodbye!
132
+
133
+ pip install gradio
134
+
135
+ Requirement already satisfied: gradio in /usr/local/lib/python3.12/dist-packages (5.50.0)
136
+ Requirement already satisfied: aiofiles<25.0,>=22.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (24.1.0)
137
+ Requirement already satisfied: anyio<5.0,>=3.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (4.12.0)
138
+ Requirement already satisfied: brotli>=1.1.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (1.2.0)
139
+ Requirement already satisfied: fastapi<1.0,>=0.115.2 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.118.3)
140
+ Requirement already satisfied: ffmpy in /usr/local/lib/python3.12/dist-packages (from gradio) (1.0.0)
141
+ Requirement already satisfied: gradio-client==1.14.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (1.14.0)
142
+ Requirement already satisfied: groovy~=0.1 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.1.2)
143
+ Requirement already satisfied: httpx<1.0,>=0.24.1 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.28.1)
144
+ Requirement already satisfied: huggingface-hub<2.0,>=0.33.5 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.36.0)
145
+ Requirement already satisfied: jinja2<4.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (3.1.6)
146
+ Requirement already satisfied: markupsafe<4.0,>=2.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (3.0.3)
147
+ Requirement already satisfied: numpy<3.0,>=1.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (2.0.2)
148
+ Requirement already satisfied: orjson~=3.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (3.11.4)
149
+ Requirement already satisfied: packaging in /usr/local/lib/python3.12/dist-packages (from gradio) (25.0)
150
+ Requirement already satisfied: pandas<3.0,>=1.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (2.2.2)
151
+ Requirement already satisfied: pillow<12.0,>=8.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (11.3.0)
152
+ Requirement already satisfied: pydantic<=2.12.3,>=2.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (2.12.3)
153
+ Requirement already satisfied: pydub in /usr/local/lib/python3.12/dist-packages (from gradio) (0.25.1)
154
+ Requirement already satisfied: python-multipart>=0.0.18 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.0.20)
155
+ Requirement already satisfied: pyyaml<7.0,>=5.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (6.0.3)
156
+ Requirement already satisfied: ruff>=0.9.3 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.14.8)
157
+ Requirement already satisfied: safehttpx<0.2.0,>=0.1.6 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.1.7)
158
+ Requirement already satisfied: semantic-version~=2.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (2.10.0)
159
+ Requirement already satisfied: starlette<1.0,>=0.40.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.48.0)
160
+ Requirement already satisfied: tomlkit<0.14.0,>=0.12.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.13.3)
161
+ Requirement already satisfied: typer<1.0,>=0.12 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.20.0)
162
+ Requirement already satisfied: typing-extensions~=4.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (4.15.0)
163
+ Requirement already satisfied: uvicorn>=0.14.0 in /usr/local/lib/python3.12/dist-packages (from gradio) (0.38.0)
164
+ Requirement already satisfied: fsspec in /usr/local/lib/python3.12/dist-packages (from gradio-client==1.14.0->gradio) (2025.3.0)
165
+ Requirement already satisfied: websockets<16.0,>=13.0 in /usr/local/lib/python3.12/dist-packages (from gradio-client==1.14.0->gradio) (15.0.1)
166
+ Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.12/dist-packages (from anyio<5.0,>=3.0->gradio) (3.11)
167
+ Requirement already satisfied: certifi in /usr/local/lib/python3.12/dist-packages (from httpx<1.0,>=0.24.1->gradio) (2025.11.12)
168
+ Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1.0,>=0.24.1->gradio) (1.0.9)
169
+ Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1.0,>=0.24.1->gradio) (0.16.0)
170
+ Requirement already satisfied: filelock in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=0.33.5->gradio) (3.20.0)
171
+ Requirement already satisfied: requests in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=0.33.5->gradio) (2.32.4)
172
+ Requirement already satisfied: tqdm>=4.42.1 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=0.33.5->gradio) (4.67.1)
173
+ Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /usr/local/lib/python3.12/dist-packages (from huggingface-hub<2.0,>=0.33.5->gradio) (1.2.0)
174
+ Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas<3.0,>=1.0->gradio) (2.9.0.post0)
175
+ Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas<3.0,>=1.0->gradio) (2025.2)
176
+ Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas<3.0,>=1.0->gradio) (2025.2)
177
+ Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.12/dist-packages (from pydantic<=2.12.3,>=2.0->gradio) (0.7.0)
178
+ Requirement already satisfied: pydantic-core==2.41.4 in /usr/local/lib/python3.12/dist-packages (from pydantic<=2.12.3,>=2.0->gradio) (2.41.4)
179
+ Requirement already satisfied: typing-inspection>=0.4.2 in /usr/local/lib/python3.12/dist-packages (from pydantic<=2.12.3,>=2.0->gradio) (0.4.2)
180
+ Requirement already satisfied: click>=8.0.0 in /usr/local/lib/python3.12/dist-packages (from typer<1.0,>=0.12->gradio) (8.3.1)
181
+ Requirement already satisfied: shellingham>=1.3.0 in /usr/local/lib/python3.12/dist-packages (from typer<1.0,>=0.12->gradio) (1.5.4)
182
+ Requirement already satisfied: rich>=10.11.0 in /usr/local/lib/python3.12/dist-packages (from typer<1.0,>=0.12->gradio) (13.9.4)
183
+ Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas<3.0,>=1.0->gradio) (1.17.0)
184
+ Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.12/dist-packages (from rich>=10.11.0->typer<1.0,>=0.12->gradio) (4.0.0)
185
+ Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.12/dist-packages (from rich>=10.11.0->typer<1.0,>=0.12->gradio) (2.19.2)
186
+ Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests->huggingface-hub<2.0,>=0.33.5->gradio) (3.4.4)
187
+ Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.12/dist-packages (from requests->huggingface-hub<2.0,>=0.33.5->gradio) (2.5.0)
188
+ Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.12/dist-packages (from markdown-it-py>=2.2.0->rich>=10.11.0->typer<1.0,>=0.12->gradio) (0.1.2)
189
+
190
+ import gradio as gr
191
+ from openai import OpenAI
192
+
193
+ client = OpenAI()
194
+
195
+ SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
196
+
197
+ Requirements:
198
+ - Maintain conversational context over multiple user turns.
199
+ - Respond helpfully and accurately to a wide range of user inputs.
200
+ - Reason about user intent before generating each response.
201
+ - Politely ask clarifying questions if a request is ambiguous or unclear.
202
+ - Avoid hallucination or speculation—respond only with information you can justify or infer from context.
203
+ - If unable to answer, politely acknowledge the limitation.
204
+
205
+ Process:
206
+ 1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
207
+ 2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
208
+ 3. If more information is needed, ask targeted clarifying questions.
209
+ 4. Output your response, maintaining natural tone and conversational flow.
210
+ 5. Continue the conversation until the user indicates they are finished.
211
+
212
+ Output:
213
+ - Each response should be in plain English, no markdown or code blocks unless explicitly requested.
214
+ - Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
215
+
216
+ Example—Instructions:
217
+ - Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
218
+ - 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?"
219
+
220
+ (For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
221
+
222
+ Edge Cases & Important Considerations:
223
+ - If the user refers to prior conversation context, recall and incorporate it.
224
+ - Be warm, engaging, and never condescending.
225
+ - If asked for code, provide only what is needed and explain concisely.
226
+
227
+ REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
228
+ """
229
+
230
+ def init_messages():
231
+ return [
232
+ {
233
+ "role": "system",
234
+ "content": [{"type": "input_text", "text": SYSTEM_PROMPT}]
235
+ }
236
+ ]
237
+
238
+ def respond(user_text, chat_history, messages):
239
+ if messages is None:
240
+ messages = init_messages()
241
+
242
+ # add user turn
243
+ messages.append(
244
+ {
245
+ "role": "user",
246
+ "content": [{"type": "input_text", "text": user_text}]
247
+ }
248
+ )
249
+
250
+ # call API
251
+ response = client.responses.create(
252
+ model="gpt-5-chat-latest",
253
+ input=messages,
254
+ text={"format": {"type": "text"}},
255
+ reasoning={},
256
+ tools=[],
257
+ temperature=1,
258
+ max_output_tokens=2048,
259
+ top_p=1,
260
+ store=True
261
+ )
262
+
263
+ assistant_text = response.output_text
264
+
265
+ # add assistant turn
266
+ messages.append(
267
+ {
268
+ "role": "assistant",
269
+ "content": [{"type": "output_text", "text": assistant_text}]
270
+ }
271
+ )
272
+
273
+ # update UI chat history
274
+ chat_history = chat_history + [(user_text, assistant_text)]
275
+
276
+ return "", chat_history, messages
277
+
278
+ with gr.Blocks() as demo:
279
+ gr.Markdown("# Python Chatbot (OpenAI Responses API)")
280
+
281
+ chatbot = gr.Chatbot(height=420)
282
+ msg = gr.Textbox(placeholder="Type your Python question and press Enter")
283
+ clear = gr.Button("Clear")
284
+
285
+ state = gr.State(init_messages())
286
+
287
+ msg.submit(
288
+ respond,
289
+ inputs=[msg, chatbot, state],
290
+ outputs=[msg, chatbot, state]
291
+ )
292
+
293
+ clear.click(
294
+ fn=lambda: ([], init_messages()),
295
+ inputs=None,
296
+ outputs=[chatbot, state]
297
+ )
298
+
299
+ demo.launch(debug=False)
300
+
301
+
302
+ /tmp/ipython-input-3281300874.py:92: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
303
+ chatbot = gr.Chatbot(height=420)
304
+ /tmp/ipython-input-3281300874.py:92: DeprecationWarning: The default value of 'allow_tags' in gr.Chatbot will be changed from False to True in Gradio 6.0. You will need to explicitly set allow_tags=False if you want to disable tags in your chatbot.
305
+ chatbot = gr.Chatbot(height=420)
306
+ It looks like you are running Gradio on a hosted Jupyter notebook, which requires `share=True`. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
307
+
308
+ Colab notebook detected. To show errors in colab notebook, set debug=True in launch()
309
+ * Running on public URL: https://4328e7e1cc6363c1c4.gradio.live
310
+
311
+ This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)
312
+
313
+ import gradio as gr
314
+ from openai import OpenAI
315
+
316
+ client = OpenAI()
317
+
318
+ SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
319
+
320
+ Requirements:
321
+ - Maintain conversational context over multiple user turns.
322
+ - Respond helpfully and accurately to a wide range of user inputs.
323
+ - Reason about user intent before generating each response.
324
+ - Politely ask clarifying questions if a request is ambiguous or unclear.
325
+ - Avoid hallucination or speculation—respond only with information you can justify or infer from context.
326
+ - If unable to answer, politely acknowledge the limitation.
327
+
328
+ Process:
329
+ 1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
330
+ 2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
331
+ 3. If more information is needed, ask targeted clarifying questions.
332
+ 4. Output your response, maintaining natural tone and conversational flow.
333
+ 5. Continue the conversation until the user indicates they are finished.
334
+
335
+ Output:
336
+ - Each response should be in plain English, no markdown or code blocks unless explicitly requested.
337
+ - Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
338
+
339
+ Example—Instructions:
340
+ - Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
341
+ - 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?"
342
+
343
+ (For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
344
+
345
+ Edge Cases & Important Considerations:
346
+ - If the user refers to prior conversation context, recall and incorporate it.
347
+ - Be warm, engaging, and never condescending.
348
+ - If asked for code, provide only what is needed and explain concisely.
349
+
350
+ REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
351
+ """
352
+
353
+ def init_messages():
354
+ return [
355
+ {
356
+ "role": "system",
357
+ "content": [{"type": "input_text", "text": SYSTEM_PROMPT}]
358
+ }
359
+ ]
360
+
361
+ def respond(user_text, chat_history, messages):
362
+ if messages is None:
363
+ messages = init_messages()
364
+
365
+ # add user turn
366
+ messages.append(
367
+ {
368
+ "role": "user",
369
+ "content": [{"type": "input_text", "text": user_text}]
370
+ }
371
+ )
372
+
373
+ # call API
374
+ response = client.responses.create(
375
+ model="gpt-5-chat-latest",
376
+ input=messages,
377
+ text={"format": {"type": "text"}},
378
+ reasoning={},
379
+ tools=[],
380
+ temperature=1.5,
381
+ max_output_tokens=6500,
382
+ top_p=0.7,
383
+ store=True
384
+ )
385
+
386
+ assistant_text = response.output_text
387
+
388
+ # add assistant turn
389
+ messages.append(
390
+ {
391
+ "role": "assistant",
392
+ "content": [{"type": "output_text", "text": assistant_text}]
393
+ }
394
+ )
395
+
396
+ # update UI chat history
397
+ chat_history = chat_history + [(user_text, assistant_text)]
398
+
399
+ return "", chat_history, messages
400
+
401
+
402
+ # -----------------------------
403
+ # Gradio UI (Upgraded)
404
+ # -----------------------------
405
+
406
+ FAQ_QUESTIONS = [
407
+ "What is the difference between a list, tuple, and set in Python?",
408
+ "How do I use dictionaries effectively in Python?",
409
+ "What are Python functions and how do *args and **kwargs work?",
410
+ "How does OOP work in Python (classes, objects, inheritance)?",
411
+ "How do I handle errors using try/except?",
412
+ "What are list comprehensions and when should I use them?",
413
+ "How do I read and write files in Python?"
414
+ ]
415
+
416
+ def set_question(q):
417
+ return q
418
+
419
+ def clear_all():
420
+ return [], init_messages(), ""
421
+
422
+ css = """
423
+ /* Overall spacing + subtle polish */
424
+ #app_container {max-width: 1200px; margin: 0 auto;}
425
+
426
+ /* Header styling */
427
+ .header-wrap {
428
+ display: flex;
429
+ align-items: center;
430
+ gap: 14px;
431
+ padding: 10px 6px 2px 6px;
432
+ }
433
+ .header-title {
434
+ font-size: 28px;
435
+ font-weight: 700;
436
+ line-height: 1.1;
437
+ }
438
+ .header-subtitle {
439
+ font-size: 12.5px;
440
+ opacity: 0.75;
441
+ margin-top: 2px;
442
+ }
443
+
444
+ /* FAQ card-like feel */
445
+ .faq-box {
446
+ border: 1px solid rgba(255,255,255,0.08);
447
+ border-radius: 12px;
448
+ padding: 14px;
449
+ }
450
+
451
+ /* Make buttons full width in FAQ column */
452
+ .faq-btn button {
453
+ width: 100%;
454
+ justify-content: flex-start;
455
+ }
456
+ """
457
+
458
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
459
+ # Header Row
460
+ with gr.Row():
461
+ with gr.Column(scale=1, min_width=80):
462
+ # Use your local file path or URL
463
+ logo = gr.Image(
464
+ value="https://github.com/Decoding-Data-Science/nov25/blob/main/logo_python.png",
465
+ label=None,
466
+ show_label=False,
467
+ show_download_button=False,
468
+ show_share_button=False,
469
+ height=64,
470
+ width=64,
471
+ container=False
472
+ )
473
+ with gr.Column(scale=10):
474
+ gr.HTML(
475
+ """
476
+
477
+
478
+ Python Tutor Bot
479
+
480
+ Ask anything about Python — concepts, debugging, best practices, and examples.
481
+
482
+
483
+
484
+ """
485
+ )
486
+
487
+ gr.Markdown("---")
488
+
489
+ # State (unchanged logic)
490
+ state = gr.State(init_messages())
491
+
492
+ # Two-column layout
493
+ with gr.Row(equal_height=True):
494
+ # LEFT: FAQ + Quick Ask
495
+ with gr.Column(scale=4, min_width=320):
496
+ with gr.Group(elem_classes=["faq-box"]):
497
+ gr.Markdown("### FAQ — Most Asked Python Questions")
498
+
499
+ gr.Markdown(
500
+ "Click a question to auto-fill it, then press **Enter** or click **Send**."
501
+ )
502
+
503
+ # Buttons for FAQ
504
+ faq_buttons = []
505
+ for q in FAQ_QUESTIONS:
506
+ b = gr.Button(q, elem_classes=["faq-btn"])
507
+ faq_buttons.append(b)
508
+
509
+ gr.Markdown("### Quick prompt ideas")
510
+ quick = gr.Radio(
511
+ choices=[
512
+ "Explain with a simple example",
513
+ "Give me a beginner-friendly analogy",
514
+ "Show common mistakes to avoid",
515
+ "Provide a short quiz question",
516
+ "Compare two approaches briefly"
517
+ ],
518
+ label="Add a style preference (optional)",
519
+ value=None
520
+ )
521
+
522
+ # RIGHT: Chat area
523
+ with gr.Column(scale=8, min_width=520):
524
+ chatbot = gr.Chatbot(
525
+ height=520,
526
+ bubble_full_width=False,
527
+ label="Conversation"
528
+ )
529
+
530
+ with gr.Row():
531
+ msg = gr.Textbox(
532
+ placeholder="Type your Python question here…",
533
+ label=None,
534
+ scale=9
535
+ )
536
+ send = gr.Button("Send", variant="primary", scale=1)
537
+
538
+ with gr.Row():
539
+ clear = gr.Button("Clear Chat")
540
+ gr.Markdown(
541
+ "Context is preserved across turns unless you clear."
542
+ )
543
+
544
+ # FAQ button -> fill textbox
545
+ for b, q in zip(faq_buttons, FAQ_QUESTIONS):
546
+ b.click(
547
+ fn=lambda q=q: set_question(q),
548
+ inputs=None,
549
+ outputs=msg
550
+ )
551
+
552
+ # Optional quick preference: append hint to textbox (UI-only)
553
+ def apply_quick_pref(pref, current_text):
554
+ if not pref:
555
+ return current_text
556
+ if current_text and current_text.strip():
557
+ return f"{current_text.strip()} ({pref})"
558
+ return pref
559
+
560
+ quick.change(
561
+ fn=apply_quick_pref,
562
+ inputs=[quick, msg],
563
+ outputs=msg
564
+ )
565
+
566
+ # Submit logic (unchanged)
567
+ msg.submit(
568
+ respond,
569
+ inputs=[msg, chatbot, state],
570
+ outputs=[msg, chatbot, state]
571
+ )
572
+
573
+ send.click(
574
+ respond,
575
+ inputs=[msg, chatbot, state],
576
+ outputs=[msg, chatbot, state]
577
+ )
578
+
579
+ # Clear
580
+ clear.click(
581
+ fn=clear_all,
582
+ inputs=None,
583
+ outputs=[chatbot, state, msg]
584
+ )
585
+
586
+ demo.launch(debug=False)
587
+
588
+
589
+ /tmp/ipython-input-427436120.py:146: DeprecationWarning: The 'theme' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'theme' to Blocks.launch() instead.
590
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
591
+ /tmp/ipython-input-427436120.py:146: DeprecationWarning: The 'css' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'css' to Blocks.launch() instead.
592
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
593
+ /tmp/ipython-input-427436120.py:212: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
594
+ chatbot = gr.Chatbot(
595
+ /tmp/ipython-input-427436120.py:212: DeprecationWarning: The 'bubble_full_width' parameter will be removed in Gradio 6.0. This parameter no longer has any effect.
596
+ chatbot = gr.Chatbot(
597
+ /tmp/ipython-input-427436120.py:212: DeprecationWarning: The default value of 'allow_tags' in gr.Chatbot will be changed from False to True in Gradio 6.0. You will need to explicitly set allow_tags=False if you want to disable tags in your chatbot.
598
+ chatbot = gr.Chatbot(
599
+ It looks like you are running Gradio on a hosted Jupyter notebook, which requires `share=True`. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
600
+
601
+ Colab notebook detected. To show errors in colab notebook, set debug=True in launch()
602
+ * Running on public URL: https://51e5ecaf20484f2021.gradio.live
603
+
604
+ This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)
605
+
606
+ import gradio as gr
607
+ from openai import OpenAI
608
+
609
+ client = OpenAI()
610
+
611
+ # RAW GitHub URL so it renders correctly
612
+ LOGO_URL = "https://raw.githubusercontent.com/Decoding-Data-Science/nov25/main/logo_python.png"
613
+
614
+ SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
615
+
616
+ Requirements:
617
+ - Maintain conversational context over multiple user turns.
618
+ - Respond helpfully and accurately to a wide range of user inputs.
619
+ - Reason about user intent before generating each response.
620
+ - Politely ask clarifying questions if a request is ambiguous or unclear.
621
+ - Avoid hallucination or speculation—respond only with information you can justify or infer from context.
622
+ - If unable to answer, politely acknowledge the limitation.
623
+
624
+ Process:
625
+ 1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
626
+ 2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
627
+ 3. If more information is needed, ask targeted clarifying questions.
628
+ 4. Output your response, maintaining natural tone and conversational flow.
629
+ 5. Continue the conversation until the user indicates they are finished.
630
+
631
+ Output:
632
+ - Each response should be in plain English, no markdown or code blocks unless explicitly requested.
633
+ - Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
634
+
635
+ Example—Instructions:
636
+ - Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
637
+ - 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?"
638
+
639
+ (For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
640
+
641
+ Edge Cases & Important Considerations:
642
+ - If the user refers to prior conversation context, recall and incorporate it.
643
+ - Be warm, engaging, and never condescending.
644
+ - If asked for code, provide only what is needed and explain concisely.
645
+
646
+ REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
647
+ """
648
+
649
+ def build_initial_messages():
650
+ return [
651
+ {
652
+ "role": "system",
653
+ "content": [{"type": "input_text", "text": SYSTEM_PROMPT}]
654
+ }
655
+ ]
656
+
657
+ def chat_fn(user_message, history, messages_state):
658
+ if messages_state is None:
659
+ messages_state = build_initial_messages()
660
+
661
+ # Add user message to state
662
+ messages_state.append(
663
+ {
664
+ "role": "user",
665
+ "content": [{"type": "input_text", "text": user_message}]
666
+ }
667
+ )
668
+
669
+ # Call Responses API
670
+ resp = client.responses.create(
671
+ model="gpt-5-chat-latest",
672
+ input=messages_state,
673
+ text={"format": {"type": "text"}},
674
+ reasoning={},
675
+ tools=[],
676
+ temperature=1,
677
+ max_output_tokens=2048,
678
+ top_p=1,
679
+ store=True
680
+ )
681
+
682
+ assistant_message = resp.output_text
683
+
684
+ # Add assistant message to state
685
+ messages_state.append(
686
+ {
687
+ "role": "assistant",
688
+ "content": [{"type": "output_text", "text": assistant_message}]
689
+ }
690
+ )
691
+
692
+ # Update visible chat
693
+ history = history + [(user_message, assistant_message)]
694
+
695
+ return "", history, messages_state
696
+
697
+ def reset_chat():
698
+ return [], build_initial_messages()
699
+
700
+ with gr.Blocks() as demo:
701
+ # Header with logo at native size (no width/height restriction)
702
+ gr.Markdown(
703
+ f"""
704
+
705
+
706
+
707
+ Python Chatbot
708
+ Powered by OpenAI Responses API
709
+
710
+
711
+ """
712
+ )
713
+
714
+ chatbot = gr.Chatbot(height=420)
715
+
716
+ input_box = gr.Textbox(
717
+ placeholder="Type your Python question and press Enter",
718
+ show_label=False
719
+ )
720
+
721
+ clear_btn = gr.Button("Clear")
722
+
723
+ messages_state = gr.State(build_initial_messages())
724
+
725
+ input_box.submit(
726
+ fn=chat_fn,
727
+ inputs=[input_box, chatbot, messages_state],
728
+ outputs=[input_box, chatbot, messages_state]
729
+ )
730
+
731
+ clear_btn.click(
732
+ fn=reset_chat,
733
+ inputs=None,
734
+ outputs=[chatbot, messages_state]
735
+ )
736
+
737
+ demo.launch(debug=False)
738
+
739
+
740
+ /tmp/ipython-input-2076293516.py:109: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
741
+ chatbot = gr.Chatbot(height=420)
742
+ /tmp/ipython-input-2076293516.py:109: DeprecationWarning: The default value of 'allow_tags' in gr.Chatbot will be changed from False to True in Gradio 6.0. You will need to explicitly set allow_tags=False if you want to disable tags in your chatbot.
743
+ chatbot = gr.Chatbot(height=420)
744
+ It looks like you are running Gradio on a hosted Jupyter notebook, which requires `share=True`. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
745
+
746
+ Colab notebook detected. To show errors in colab notebook, set debug=True in launch()
747
+ * Running on public URL: https://2176d4ed63f9c61546.gradio.live
748
+
749
+ This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)
750
+
751
+ import gradio as gr
752
+ from openai import OpenAI
753
+
754
+ client = OpenAI()
755
+
756
+ # Use the RAW GitHub URL so the image loads correctly
757
+ LOGO_URL = "https://raw.githubusercontent.com/Decoding-Data-Science/nov25/main/logo_python.png"
758
+
759
+ SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
760
+
761
+ Requirements:
762
+ - Maintain conversational context over multiple user turns.
763
+ - Respond helpfully and accurately to a wide range of user inputs.
764
+ - Reason about user intent before generating each response.
765
+ - Politely ask clarifying questions if a request is ambiguous or unclear.
766
+ - Avoid hallucination or speculation—respond only with information you can justify or infer from context.
767
+ - If unable to answer, politely acknowledge the limitation.
768
+
769
+ Process:
770
+ 1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
771
+ 2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
772
+ 3. If more information is needed, ask targeted clarifying questions.
773
+ 4. Output your response, maintaining natural tone and conversational flow.
774
+ 5. Continue the conversation until the user indicates they are finished.
775
+
776
+ Output:
777
+ - Each response should be in plain English, no markdown or code blocks unless explicitly requested.
778
+ - Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
779
+
780
+ Example—Instructions:
781
+ - Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
782
+ - 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?"
783
+
784
+ (For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
785
+
786
+ Edge Cases & Important Considerations:
787
+ - If the user refers to prior conversation context, recall and incorporate it.
788
+ - Be warm, engaging, and never condescending.
789
+ - If asked for code, provide only what is needed and explain concisely.
790
+
791
+ REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
792
+ """
793
+
794
+ def build_initial_messages():
795
+ return [
796
+ {
797
+ "role": "system",
798
+ "content": [{"type": "input_text", "text": SYSTEM_PROMPT}]
799
+ }
800
+ ]
801
+
802
+ def chat_fn(user_message, history, messages_state):
803
+ # Initialize state if needed
804
+ if messages_state is None:
805
+ messages_state = build_initial_messages()
806
+
807
+ # Append user input
808
+ messages_state.append(
809
+ {
810
+ "role": "user",
811
+ "content": [{"type": "input_text", "text": user_message}]
812
+ }
813
+ )
814
+
815
+ # Call Responses API
816
+ resp = client.responses.create(
817
+ model="gpt-5-chat-latest",
818
+ input=messages_state,
819
+ text={"format": {"type": "text"}},
820
+ reasoning={},
821
+ tools=[],
822
+ temperature=1,
823
+ max_output_tokens=2048,
824
+ top_p=1,
825
+ store=True
826
+ )
827
+
828
+ assistant_message = resp.output_text
829
+
830
+ # Append assistant output
831
+ messages_state.append(
832
+ {
833
+ "role": "assistant",
834
+ "content": [{"type": "output_text", "text": assistant_message}]
835
+ }
836
+ )
837
+
838
+ # Update visible chat history
839
+ history = history + [(user_message, assistant_message)]
840
+
841
+ # Clear textbox, update chat + state
842
+ return "", history, messages_state
843
+
844
+ def reset_chat():
845
+ return [], build_initial_messages()
846
+
847
+ with gr.Blocks() as demo:
848
+ # Header with logo at native size (no constraints)
849
+ gr.Markdown(
850
+ f"""
851
+
852
+
853
+
854
+ Python Chatbot
855
+ Powered by OpenAI Responses API
856
+
857
+
858
+ """
859
+ )
860
+
861
+ chatbot = gr.Chatbot(height=420)
862
+ input_box = gr.Textbox(
863
+ placeholder="Type your Python question and press Enter",
864
+ show_label=False
865
+ )
866
+ clear_btn = gr.Button("Clear")
867
+
868
+ messages_state = gr.State(build_initial_messages())
869
+
870
+ input_box.submit(
871
+ fn=chat_fn,
872
+ inputs=[input_box, chatbot, messages_state],
873
+ outputs=[input_box, chatbot, messages_state]
874
+ )
875
+
876
+ clear_btn.click(
877
+ fn=reset_chat,
878
+ inputs=None,
879
+ outputs=[chatbot, messages_state]
880
+ )
881
+
882
+ demo.launch(debug=False)
883
+
884
+
885
+ /tmp/ipython-input-174110024.py:111: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
886
+ chatbot = gr.Chatbot(height=420)
887
+ /tmp/ipython-input-174110024.py:111: DeprecationWarning: The default value of 'allow_tags' in gr.Chatbot will be changed from False to True in Gradio 6.0. You will need to explicitly set allow_tags=False if you want to disable tags in your chatbot.
888
+ chatbot = gr.Chatbot(height=420)
889
+ It looks like you are running Gradio on a hosted Jupyter notebook, which requires `share=True`. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
890
+
891
+ Colab notebook detected. To show errors in colab notebook, set debug=True in launch()
892
+ * Running on public URL: https://c359b3bd72c7292eb9.gradio.live
893
+
894
+ This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)
895
+
896
+ import gradio as gr
897
+ from openai import OpenAI
898
+
899
+ client = OpenAI()
900
+
901
+ SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
902
+
903
+ Requirements:
904
+ - Maintain conversational context over multiple user turns.
905
+ - Respond helpfully and accurately to a wide range of user inputs.
906
+ - Reason about user intent before generating each response.
907
+ - Politely ask clarifying questions if a request is ambiguous or unclear.
908
+ - Avoid hallucination or speculation—respond only with information you can justify or infer from context.
909
+ - If unable to answer, politely acknowledge the limitation.
910
+
911
+ Process:
912
+ 1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
913
+ 2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
914
+ 3. If more information is needed, ask targeted clarifying questions.
915
+ 4. Output your response, maintaining natural tone and conversational flow.
916
+ 5. Continue the conversation until the user indicates they are finished.
917
+
918
+ Output:
919
+ - Each response should be in plain English, no markdown or code blocks unless explicitly requested.
920
+ - Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
921
+
922
+ Example—Instructions:
923
+ - Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
924
+ - 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?"
925
+
926
+ (For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
927
+
928
+ Edge Cases & Important Considerations:
929
+ - If the user refers to prior conversation context, recall and incorporate it.
930
+ - Be warm, engaging, and never condescending.
931
+ - If asked for code, provide only what is needed and explain concisely.
932
+
933
+ REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
934
+ """
935
+
936
+ def init_messages():
937
+ return [
938
+ {
939
+ "role": "system",
940
+ "content": [{"type": "input_text", "text": SYSTEM_PROMPT}]
941
+ }
942
+ ]
943
+
944
+ def respond(user_text, chat_history, messages):
945
+ if messages is None:
946
+ messages = init_messages()
947
+
948
+ # add user turn
949
+ messages.append(
950
+ {
951
+ "role": "user",
952
+ "content": [{"type": "input_text", "text": user_text}]
953
+ }
954
+ )
955
+
956
+ # call API
957
+ response = client.responses.create(
958
+ model="gpt-5-chat-latest",
959
+ input=messages,
960
+ text={"format": {"type": "text"}},
961
+ reasoning={},
962
+ tools=[],
963
+ temperature=1,
964
+ max_output_tokens=2048,
965
+ top_p=1,
966
+ store=True
967
+ )
968
+
969
+ assistant_text = response.output_text
970
+
971
+ # add assistant turn
972
+ messages.append(
973
+ {
974
+ "role": "assistant",
975
+ "content": [{"type": "output_text", "text": assistant_text}]
976
+ }
977
+ )
978
+
979
+ # update UI chat history
980
+ chat_history = chat_history + [(user_text, assistant_text)]
981
+
982
+ return "", chat_history, messages
983
+
984
+
985
+ # -----------------------------
986
+ # Gradio UI (Upgraded)
987
+ # -----------------------------
988
+
989
+ FAQ_QUESTIONS = [
990
+ "What is the difference between a list, tuple, and set in Python?",
991
+ "How do I use dictionaries effectively in Python?",
992
+ "What are Python functions and how do *args and **kwargs work?",
993
+ "How does OOP work in Python (classes, objects, inheritance)?",
994
+ "How do I handle errors using try/except?",
995
+ "What are list comprehensions and when should I use them?",
996
+ "How do I read and write files in Python?"
997
+ ]
998
+
999
+ def set_question(q):
1000
+ return q
1001
+
1002
+ def clear_all():
1003
+ return [], init_messages(), ""
1004
+
1005
+ # Updated logo URL (RAW link)
1006
+ LOGO_URL = "https://raw.githubusercontent.com/Decoding-Data-Science/nov25/main/logo_python.png"
1007
+
1008
+ css = """
1009
+ /* Overall spacing + subtle polish */
1010
+ #app_container {max-width: 1200px; margin: 0 auto;}
1011
+
1012
+ /* Header styling */
1013
+ .header-wrap {
1014
+ display: flex;
1015
+ align-items: center;
1016
+ gap: 14px;
1017
+ padding: 10px 6px 2px 6px;
1018
+ }
1019
+ .header-title {
1020
+ font-size: 28px;
1021
+ font-weight: 700;
1022
+ line-height: 1.1;
1023
+ }
1024
+ .header-subtitle {
1025
+ font-size: 12.5px;
1026
+ opacity: 0.75;
1027
+ margin-top: 2px;
1028
+ }
1029
+
1030
+ /* FAQ card-like feel */
1031
+ .faq-box {
1032
+ border: 1px solid rgba(255,255,255,0.08);
1033
+ border-radius: 12px;
1034
+ padding: 14px;
1035
+ }
1036
+
1037
+ /* Make buttons full width in FAQ column */
1038
+ .faq-btn button {
1039
+ width: 100%;
1040
+ justify-content: flex-start;
1041
+ }
1042
+ """
1043
+
1044
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
1045
+ # Header Row
1046
+ with gr.Row():
1047
+ with gr.Column(scale=1, min_width=80):
1048
+ logo = gr.Image(
1049
+ value=LOGO_URL, # ✅ updated to raw URL
1050
+ label=None,
1051
+ show_label=False,
1052
+ show_download_button=False,
1053
+ show_share_button=False,
1054
+ height=64,
1055
+ width=64,
1056
+ container=False
1057
+ )
1058
+ with gr.Column(scale=10):
1059
+ gr.HTML(
1060
+ """
1061
+
1062
+
1063
+ Python Tutor Bot
1064
+
1065
+ Ask anything about Python — concepts, debugging, best practices, and examples.
1066
+
1067
+
1068
+
1069
+ """
1070
+ )
1071
+
1072
+ gr.Markdown("---")
1073
+
1074
+ # State (unchanged logic)
1075
+ state = gr.State(init_messages())
1076
+
1077
+ # Two-column layout
1078
+ with gr.Row(equal_height=True):
1079
+ # LEFT: FAQ + Quick Ask
1080
+ with gr.Column(scale=4, min_width=320):
1081
+ with gr.Group(elem_classes=["faq-box"]):
1082
+ gr.Markdown("### FAQ — Most Asked Python Questions")
1083
+
1084
+ gr.Markdown(
1085
+ "Click a question to auto-fill it, then press **Enter** or click **Send**."
1086
+ )
1087
+
1088
+ # Buttons for FAQ
1089
+ faq_buttons = []
1090
+ for q in FAQ_QUESTIONS:
1091
+ b = gr.Button(q, elem_classes=["faq-btn"])
1092
+ faq_buttons.append(b)
1093
+
1094
+ gr.Markdown("### Quick prompt ideas")
1095
+ quick = gr.Radio(
1096
+ choices=[
1097
+ "Explain with a simple example",
1098
+ "Give me a beginner-friendly analogy",
1099
+ "Show common mistakes to avoid",
1100
+ "Provide a short quiz question",
1101
+ "Compare two approaches briefly"
1102
+ ],
1103
+ label="Add a style preference (optional)",
1104
+ value=None
1105
+ )
1106
+
1107
+ # RIGHT: Chat area
1108
+ with gr.Column(scale=8, min_width=520):
1109
+ chatbot = gr.Chatbot(
1110
+ height=520,
1111
+ bubble_full_width=False,
1112
+ label="Conversation"
1113
+ )
1114
+
1115
+ with gr.Row():
1116
+ msg = gr.Textbox(
1117
+ placeholder="Type your Python question here…",
1118
+ label=None,
1119
+ scale=9
1120
+ )
1121
+ send = gr.Button("Send", variant="primary", scale=1)
1122
+
1123
+ with gr.Row():
1124
+ clear = gr.Button("Clear Chat")
1125
+ gr.Markdown(
1126
+ "Context is preserved across turns unless you clear."
1127
+ )
1128
+
1129
+ # FAQ button -> fill textbox
1130
+ for b, q in zip(faq_buttons, FAQ_QUESTIONS):
1131
+ b.click(
1132
+ fn=lambda q=q: set_question(q),
1133
+ inputs=None,
1134
+ outputs=msg
1135
+ )
1136
+
1137
+ # Optional quick preference: append hint to textbox (UI-only)
1138
+ def apply_quick_pref(pref, current_text):
1139
+ if not pref:
1140
+ return current_text
1141
+ if current_text and current_text.strip():
1142
+ return f"{current_text.strip()} ({pref})"
1143
+ return pref
1144
+
1145
+ quick.change(
1146
+ fn=apply_quick_pref,
1147
+ inputs=[quick, msg],
1148
+ outputs=msg
1149
+ )
1150
+
1151
+ # Submit logic (unchanged)
1152
+ msg.submit(
1153
+ respond,
1154
+ inputs=[msg, chatbot, state],
1155
+ outputs=[msg, chatbot, state]
1156
+ )
1157
+
1158
+ send.click(
1159
+ respond,
1160
+ inputs=[msg, chatbot, state],
1161
+ outputs=[msg, chatbot, state]
1162
+ )
1163
+
1164
+ # Clear
1165
+ clear.click(
1166
+ fn=clear_all,
1167
+ inputs=None,
1168
+ outputs=[chatbot, state, msg]
1169
+ )
1170
+
1171
+ demo.launch(debug=False)
1172
+
1173
+
1174
+ /tmp/ipython-input-1706520990.py:149: DeprecationWarning: The 'theme' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'theme' to Blocks.launch() instead.
1175
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
1176
+ /tmp/ipython-input-1706520990.py:149: DeprecationWarning: The 'css' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'css' to Blocks.launch() instead.
1177
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
1178
+ /tmp/ipython-input-1706520990.py:214: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
1179
+ chatbot = gr.Chatbot(
1180
+ /tmp/ipython-input-1706520990.py:214: DeprecationWarning: The 'bubble_full_width' parameter will be removed in Gradio 6.0. This parameter no longer has any effect.
1181
+ chatbot = gr.Chatbot(
1182
+ /tmp/ipython-input-1706520990.py:214: DeprecationWarning: The default value of 'allow_tags' in gr.Chatbot will be changed from False to True in Gradio 6.0. You will need to explicitly set allow_tags=False if you want to disable tags in your chatbot.
1183
+ chatbot = gr.Chatbot(
1184
+ It looks like you are running Gradio on a hosted Jupyter notebook, which requires `share=True`. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
1185
+
1186
+ Colab notebook detected. To show errors in colab notebook, set debug=True in launch()
1187
+ * Running on public URL: https://1820f7af2565ad2f97.gradio.live
1188
+
1189
+ This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)
1190
+ Steps to deploy on Hugging Face Spaces (Gradio)
1191
+ Hugging Face → New Space
1192
+
1193
+ Choose Gradio as SDK. This sets your Space to use Gradio via the README config. Hugging Face
1194
+
1195
+ Pick a name and visibility.
1196
+
1197
+ Add files
1198
+
1199
+ app.py (your code).
1200
+
1201
+ requirements.txt.
1202
+
1203
+ requirements.txt Use something like:
1204
+
1205
+ gradio openai
1206
+
1207
+ Add your secret
1208
+ Go to your Space Settings → Variables and secrets.
1209
+
1210
+ Under Secrets, add:
1211
+
1212
+ Name: OPENAI_API_KEY
1213
+
1214
+ Value: your key Secrets are injected into the runtime as environment variables. Hugging Face
1215
+
1216
+ Commit
1217
+
1218
+ If you’re editing in the browser, just save/commit.
1219
+
1220
+ The Space will rebuild and launch automatically.
1221
+
1222
+
1223
+
1224
+
1225
+ # ADD THIS IN APP.PY
1226
+
1227
+
1228
+
1229
+
1230
+ import os
1231
+ import gradio as gr
1232
+ from openai import OpenAI
1233
+
1234
+ # -----------------------------
1235
+ # Load OpenAI key from HF Secrets
1236
+ # -----------------------------
1237
+ # In Hugging Face Spaces, Secrets/Variables are available as environment variables.
1238
+ # Add this in your Space Settings -> Variables and secrets -> Secrets
1239
+ # Key name: OPENAI_API_KEY
1240
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
1241
+
1242
+
1243
+
1244
+ client = OpenAI(api_key=OPENAI_API_KEY)
1245
+
1246
+ SYSTEM_PROMPT = """Create an intelligent Python chatbot capable of engaging in natural, helpful, and contextually appropriate conversations with human users.
1247
+
1248
+ Requirements:
1249
+ - Maintain conversational context over multiple user turns.
1250
+ - Respond helpfully and accurately to a wide range of user inputs.
1251
+ - Reason about user intent before generating each response.
1252
+ - Politely ask clarifying questions if a request is ambiguous or unclear.
1253
+ - Avoid hallucination or speculation—respond only with information you can justify or infer from context.
1254
+ - If unable to answer, politely acknowledge the limitation.
1255
+
1256
+ Process:
1257
+ 1. On each user message, first analyze prior context (if any) and what the user is likely asking/intending.
1258
+ 2. Think step-by-step (chain-of-thought) to determine the most relevant, helpful response. Always reason internally before presenting your answer.
1259
+ 3. If more information is needed, ask targeted clarifying questions.
1260
+ 4. Output your response, maintaining natural tone and conversational flow.
1261
+ 5. Continue the conversation until the user indicates they are finished.
1262
+
1263
+ Output:
1264
+ - Each response should be in plain English, no markdown or code blocks unless explicitly requested.
1265
+ - Maintain a single-paragraph, natural-sounding chat response of 1–3 sentences (unless a longer reply is requested or required).
1266
+
1267
+ Example—Instructions:
1268
+ - Reasoning: "Recognize the user asked for Python list examples and may want to know how lists work."
1269
+ - 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?"
1270
+
1271
+ (For more advanced technical requests, reasoning steps and explanations may be slightly longer, but always conclude with a concise, clear reply to the user.)
1272
+
1273
+ Edge Cases & Important Considerations:
1274
+ - If the user refers to prior conversation context, recall and incorporate it.
1275
+ - Be warm, engaging, and never condescending.
1276
+ - If asked for code, provide only what is needed and explain concisely.
1277
+
1278
+ REMINDER: Your primary objective is to serve as a helpful Python chatbot, reasoning about context before each response, and outputting clear, appropriate conversational replies.
1279
+ """
1280
+
1281
+ def init_messages():
1282
+ return [
1283
+ {
1284
+ "role": "system",
1285
+ "content": [{"type": "input_text", "text": SYSTEM_PROMPT}]
1286
+ }
1287
+ ]
1288
+
1289
+ def respond(user_text, chat_history, messages):
1290
+ if messages is None:
1291
+ messages = init_messages()
1292
+
1293
+ # add user turn
1294
+ messages.append(
1295
+ {
1296
+ "role": "user",
1297
+ "content": [{"type": "input_text", "text": user_text}]
1298
+ }
1299
+ )
1300
+
1301
+ # call API
1302
+ response = client.responses.create(
1303
+ model="gpt-5-chat-latest",
1304
+ input=messages,
1305
+ text={"format": {"type": "text"}},
1306
+ reasoning={},
1307
+ tools=[],
1308
+ temperature=1,
1309
+ max_output_tokens=2048,
1310
+ top_p=1,
1311
+ store=True
1312
+ )
1313
+
1314
+ assistant_text = response.output_text
1315
+
1316
+ # add assistant turn
1317
+ messages.append(
1318
+ {
1319
+ "role": "assistant",
1320
+ "content": [{"type": "output_text", "text": assistant_text}]
1321
+ }
1322
+ )
1323
+
1324
+ # update UI chat history
1325
+ chat_history = chat_history + [(user_text, assistant_text)]
1326
+
1327
+ return "", chat_history, messages
1328
+
1329
+
1330
+ # -----------------------------
1331
+ # Gradio UI (Upgraded)
1332
+ # -----------------------------
1333
+
1334
+ FAQ_QUESTIONS = [
1335
+ "What is the difference between a list, tuple, and set in Python?",
1336
+ "How do I use dictionaries effectively in Python?",
1337
+ "What are Python functions and how do *args and **kwargs work?",
1338
+ "How does OOP work in Python (classes, objects, inheritance)?",
1339
+ "How do I handle errors using try/except?",
1340
+ "What are list comprehensions and when should I use them?",
1341
+ "How do I read and write files in Python?"
1342
+ ]
1343
+
1344
+ def set_question(q):
1345
+ return q
1346
+
1347
+ def clear_all():
1348
+ return [], init_messages(), ""
1349
+
1350
+ # Updated logo URL (RAW link)
1351
+ LOGO_URL = "https://raw.githubusercontent.com/Decoding-Data-Science/nov25/main/logo_python.png"
1352
+
1353
+ css = """
1354
+ /* Overall spacing + subtle polish */
1355
+ #app_container {max-width: 1200px; margin: 0 auto;}
1356
+
1357
+ /* Header styling */
1358
+ .header-wrap {
1359
+ display: flex;
1360
+ align-items: center;
1361
+ gap: 14px;
1362
+ padding: 10px 6px 2px 6px;
1363
+ }
1364
+ .header-title {
1365
+ font-size: 28px;
1366
+ font-weight: 700;
1367
+ line-height: 1.1;
1368
+ }
1369
+ .header-subtitle {
1370
+ font-size: 12.5px;
1371
+ opacity: 0.75;
1372
+ margin-top: 2px;
1373
+ }
1374
+
1375
+ /* FAQ card-like feel */
1376
+ .faq-box {
1377
+ border: 1px solid rgba(255,255,255,0.08);
1378
+ border-radius: 12px;
1379
+ padding: 14px;
1380
+ }
1381
+
1382
+ /* Make buttons full width in FAQ column */
1383
+ .faq-btn button {
1384
+ width: 100%;
1385
+ justify-content: flex-start;
1386
+ }
1387
+ """
1388
+
1389
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
1390
+ # Header Row
1391
+ with gr.Row():
1392
+ with gr.Column(scale=1, min_width=80):
1393
+ logo = gr.Image(
1394
+ value=LOGO_URL,
1395
+ label=None,
1396
+ show_label=False,
1397
+ show_download_button=False,
1398
+ show_share_button=False,
1399
+ height=64,
1400
+ width=64,
1401
+ container=False
1402
+ )
1403
+ with gr.Column(scale=10):
1404
+ gr.HTML(
1405
+ """
1406
+
1407
+
1408
+ Python Tutor Bot
1409
+
1410
+ Ask anything about Python — concepts, debugging, best practices, and examples.
1411
+
1412
+
1413
+
1414
+ """
1415
+ )
1416
+
1417
+ gr.Markdown("---")
1418
+
1419
+ # State (unchanged logic)
1420
+ state = gr.State(init_messages())
1421
+
1422
+ # Two-column layout
1423
+ with gr.Row(equal_height=True):
1424
+ # LEFT: FAQ + Quick Ask
1425
+ with gr.Column(scale=4, min_width=320):
1426
+ with gr.Group(elem_classes=["faq-box"]):
1427
+ gr.Markdown("### FAQ — Most Asked Python Questions")
1428
+
1429
+ gr.Markdown(
1430
+ "Click a question to auto-fill it, then press **Enter** or click **Send**."
1431
+ )
1432
+
1433
+ # Buttons for FAQ
1434
+ faq_buttons = []
1435
+ for q in FAQ_QUESTIONS:
1436
+ b = gr.Button(q, elem_classes=["faq-btn"])
1437
+ faq_buttons.append(b)
1438
+
1439
+ gr.Markdown("### Quick prompt ideas")
1440
+ quick = gr.Radio(
1441
+ choices=[
1442
+ "Explain with a simple example",
1443
+ "Give me a beginner-friendly analogy",
1444
+ "Show common mistakes to avoid",
1445
+ "Provide a short quiz question",
1446
+ "Compare two approaches briefly"
1447
+ ],
1448
+ label="Add a style preference (optional)",
1449
+ value=None
1450
+ )
1451
+
1452
+ # RIGHT: Chat area
1453
+ with gr.Column(scale=8, min_width=520):
1454
+ chatbot = gr.Chatbot(
1455
+ height=520,
1456
+ bubble_full_width=False,
1457
+ label="Conversation"
1458
+ )
1459
+
1460
+ with gr.Row():
1461
+ msg = gr.Textbox(
1462
+ placeholder="Type your Python question here…",
1463
+ label=None,
1464
+ scale=9
1465
+ )
1466
+ send = gr.Button("Send", variant="primary", scale=1)
1467
+
1468
+ with gr.Row():
1469
+ clear = gr.Button("Clear Chat")
1470
+ gr.Markdown(
1471
+ "Context is preserved across turns unless you clear."
1472
+ )
1473
+
1474
+ # FAQ button -> fill textbox
1475
+ for b, q in zip(faq_buttons, FAQ_QUESTIONS):
1476
+ b.click(
1477
+ fn=lambda q=q: set_question(q),
1478
+ inputs=None,
1479
+ outputs=msg
1480
+ )
1481
+
1482
+ # Optional quick preference: append hint to textbox (UI-only)
1483
+ def apply_quick_pref(pref, current_text):
1484
+ if not pref:
1485
+ return current_text
1486
+ if current_text and current_text.strip():
1487
+ return f"{current_text.strip()} ({pref})"
1488
+ return pref
1489
+
1490
+ quick.change(
1491
+ fn=apply_quick_pref,
1492
+ inputs=[quick, msg],
1493
+ outputs=msg
1494
+ )
1495
+
1496
+ # Submit logic (unchanged)
1497
+ msg.submit(
1498
+ respond,
1499
+ inputs=[msg, chatbot, state],
1500
+ outputs=[msg, chatbot, state]
1501
+ )
1502
+
1503
+ send.click(
1504
+ respond,
1505
+ inputs=[msg, chatbot, state],
1506
+ outputs=[msg, chatbot, state]
1507
+ )
1508
+
1509
+ # Clear
1510
+ clear.click(
1511
+ fn=clear_all,
1512
+ inputs=None,
1513
+ outputs=[chatbot, state, msg]
1514
+ )
1515
+
1516
+ demo.launch(debug=False)
1517
+
1518
+
1519
+ /tmp/ipython-input-1442312891.py:165: DeprecationWarning: The 'theme' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'theme' to Blocks.launch() instead.
1520
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
1521
+ /tmp/ipython-input-1442312891.py:165: DeprecationWarning: The 'css' parameter in the Blocks constructor will be removed in Gradio 6.0. You will need to pass 'css' to Blocks.launch() instead.
1522
+ with gr.Blocks(css=css, theme=gr.themes.Soft(), elem_id="app_container") as demo:
1523
+ /tmp/ipython-input-1442312891.py:230: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.
1524
+ chatbot = gr.Chatbot(
1525
+ /tmp/ipython-input-1442312891.py:230: DeprecationWarning: The 'bubble_full_width' parameter will be removed in Gradio 6.0. This parameter no longer has any effect.
1526
+ chatbot = gr.Chatbot(
1527
+ /tmp/ipython-input-1442312891.py:230: DeprecationWarning: The default value of 'allow_tags' in gr.Chatbot will be changed from False to True in Gradio 6.0. You will need to explicitly set allow_tags=False if you want to disable tags in your chatbot.
1528
+ chatbot = gr.Chatbot(
1529
+ It looks like you are running Gradio on a hosted Jupyter notebook, which requires `share=True`. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).
1530
+
1531
+ Colab notebook detected. To show errors in colab notebook, set debug=True in launch()
1532
+ * Running on public URL: https://0fe9497c9e2c0ee0fc.gradio.live
1533
+
1534
+ This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)