File size: 12,471 Bytes
437a1c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import os
import traceback
from typing import Any

import gradio as gr
from openai import OpenAI


GENERATION_MODELS = [
    "gpt-4.1-mini",
    "gpt-4.1",
    "gpt-4o-mini",
    "gpt-5.5",
]

REASONING_MODELS = [
    "gpt-5.5",
    "o4-mini",
    "o3-mini",
]


def get_client() -> OpenAI | None:
    """
    Hugging Face Spaces exposes Secrets as environment variables.
    Add your OpenAI key in Space Settings as OPENAI_API_KEY.
    The lowercase fallback is included only to help during local testing.
    """
    api_key = os.getenv("OPENAI_API_KEY") or os.getenv("openai_api_key")
    if not api_key:
        return None
    return OpenAI(api_key=api_key)


def extract_output_text(response: Any) -> str:
    """Robustly extract text from an OpenAI Responses API response."""
    output_text = getattr(response, "output_text", None)
    if output_text:
        return output_text.strip()

    chunks: list[str] = []
    for item in getattr(response, "output", []) or []:
        content = getattr(item, "content", None)
        if content is None and isinstance(item, dict):
            content = item.get("content", [])

        for part in content or []:
            if isinstance(part, dict):
                text = part.get("text") or part.get("output_text")
            else:
                text = getattr(part, "text", None) or getattr(part, "output_text", None)
            if text:
                chunks.append(str(text))

    return "\n".join(chunks).strip() if chunks else str(response)


def is_gpt5_family(model: str) -> bool:
    """
    GPT-5 family models may reject custom sampling controls such as temperature.
    To avoid the common 400 error, this app does not send those controls to GPT-5.x models.
    """
    return model.strip().lower().startswith("gpt-5")


def format_settings(title: str, settings: dict[str, Any]) -> str:
    lines = [f"--- {title} ---"]
    for key, value in settings.items():
        lines.append(f"{key}: {value}")
    lines.append("------------------------\n")
    return "\n".join(lines)


def run_generation(
    prompt: str,
    model: str,
    system_message: str,
    temperature: float,
    top_p: float,
    max_output_tokens: int,
    frequency_penalty: float,
    presence_penalty: float,
    show_settings: bool,
) -> str:
    client = get_client()
    if client is None:
        return (
            "Missing API key.\n\n"
            "In Hugging Face Spaces, go to Settings → Secrets and add:\n"
            "Name: OPENAI_API_KEY\n"
            "Value: your OpenAI API key"
        )

    if not prompt or not prompt.strip():
        return "Please enter a prompt."

    params: dict[str, Any] = {
        "model": model,
        "instructions": system_message or "You are a helpful assistant.",
        "input": prompt,
        "max_output_tokens": int(max_output_tokens),
    }

    settings_note = ""
    if is_gpt5_family(model):
        settings_note = (
            "Note: GPT-5 family models can reject custom sampling controls. "
            "Temperature, top_p, frequency_penalty, and presence_penalty were not sent.\n\n"
        )
    else:
        params.update(
            {
                "temperature": float(temperature),
                "top_p": float(top_p),
                "frequency_penalty": float(frequency_penalty),
                "presence_penalty": float(presence_penalty),
            }
        )

    try:
        response = client.responses.create(**params)
        text = extract_output_text(response)

        if show_settings:
            settings = {
                "model": model,
                "system_message": system_message,
                "max_output_tokens": max_output_tokens,
            }
            if is_gpt5_family(model):
                settings.update(
                    {
                        "sampling_controls": "not sent for GPT-5 family model",
                    }
                )
            else:
                settings.update(
                    {
                        "temperature": temperature,
                        "top_p": top_p,
                        "frequency_penalty": frequency_penalty,
                        "presence_penalty": presence_penalty,
                    }
                )
            return settings_note + format_settings("Generation Settings", settings) + text

        return settings_note + text

    except Exception as exc:
        return (
            "OpenAI API error:\n"
            f"{exc}\n\n"
            "Tip: If you selected a GPT-5 family model, try keeping generation controls at default "
            "or use the Reasoning Controls tab.\n\n"
            f"Technical details:\n{traceback.format_exc()}"
        )


def run_reasoning(
    prompt: str,
    model: str,
    reasoning_effort: str,
    max_output_tokens: int,
    show_settings: bool,
) -> str:
    client = get_client()
    if client is None:
        return (
            "Missing API key.\n\n"
            "In Hugging Face Spaces, go to Settings → Secrets and add:\n"
            "Name: OPENAI_API_KEY\n"
            "Value: your OpenAI API key"
        )

    if not prompt or not prompt.strip():
        return "Please enter a prompt."

    params: dict[str, Any] = {
        "model": model,
        "input": prompt,
        "reasoning": {"effort": reasoning_effort},
        "max_output_tokens": int(max_output_tokens),
    }

    try:
        response = client.responses.create(**params)
        text = extract_output_text(response)

        if show_settings:
            settings = {
                "model": model,
                "reasoning_effort": reasoning_effort,
                "max_output_tokens": max_output_tokens,
                "api": "OpenAI Responses API",
            }
            return format_settings("Reasoning Settings", settings) + text

        return text

    except Exception as exc:
        return (
            "OpenAI API error:\n"
            f"{exc}\n\n"
            "Tip: Make sure your account has access to the selected model, or try another model "
            "from the dropdown.\n\n"
            f"Technical details:\n{traceback.format_exc()}"
        )


custom_css = """
.gradio-container {
    max-width: 1180px !important;
    margin: auto !important;
}
#main-title {
    text-align: center;
}
.output-box textarea {
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
}
"""


with gr.Blocks(
    title="OpenAI LLM Controls",
    theme=gr.themes.Soft(),
    css=custom_css,
) as demo:
    gr.Markdown(
        """
        # OpenAI LLM Controls

        Experiment with generation settings and reasoning effort using the OpenAI Responses API.
        Add your key in Hugging Face Spaces as the secret `OPENAI_API_KEY`.
        """,
        elem_id="main-title",
    )

    with gr.Tab("Generation Controls"):
        gr.Markdown(
            """
            Use this tab to test practical writing and completion tasks.  
            For GPT-5 family models, the app avoids sending custom sampling controls to prevent unsupported-parameter errors.
            """
        )

        with gr.Row():
            with gr.Column(scale=1):
                gen_prompt = gr.Textbox(
                    lines=7,
                    label="Prompt",
                    value="Write a short LinkedIn post explaining why business leaders should learn AI. Maximum 120 words.",
                )
                gen_model = gr.Dropdown(
                    GENERATION_MODELS,
                    label="Model",
                    value="gpt-4.1-mini",
                )
                system_message = gr.Textbox(
                    lines=3,
                    label="System Message",
                    value="You are a helpful AI instructor. Keep answers clear and practical.",
                )
                with gr.Accordion("Advanced Generation Settings", open=True):
                    temperature = gr.Slider(
                        minimum=0.0,
                        maximum=2.0,
                        step=0.01,
                        value=0.7,
                        label="Temperature",
                    )
                    top_p = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        step=0.01,
                        value=1.0,
                        label="Top P",
                    )
                    max_output_tokens_gen = gr.Slider(
                        minimum=50,
                        maximum=4000,
                        step=10,
                        value=300,
                        label="Max Output Tokens",
                    )
                    frequency_penalty = gr.Slider(
                        minimum=-2.0,
                        maximum=2.0,
                        step=0.01,
                        value=0.0,
                        label="Frequency Penalty",
                    )
                    presence_penalty = gr.Slider(
                        minimum=-2.0,
                        maximum=2.0,
                        step=0.01,
                        value=0.0,
                        label="Presence Penalty",
                    )
                    show_settings_gen = gr.Checkbox(value=True, label="Show Settings")
                gen_button = gr.Button("Generate", variant="primary")

            with gr.Column(scale=1):
                gen_output = gr.Textbox(
                    lines=22,
                    label="Output",
                    elem_classes=["output-box"],
                    show_copy_button=True,
                )

        gen_button.click(
            fn=run_generation,
            inputs=[
                gen_prompt,
                gen_model,
                system_message,
                temperature,
                top_p,
                max_output_tokens_gen,
                frequency_penalty,
                presence_penalty,
                show_settings_gen,
            ],
            outputs=gen_output,
        )

    with gr.Tab("Reasoning Controls"):
        gr.Markdown(
            """
            Use this tab for analysis, recommendations, technical trade-offs, planning, and decision-making tasks.
            """
        )

        with gr.Row():
            with gr.Column(scale=1):
                reason_prompt = gr.Textbox(
                    lines=9,
                    label="Prompt",
                    value=(
                        "A telecom company wants to build an AI customer support assistant. "
                        "They have 50,000 past support tickets, a FAQ website, billing policies, "
                        "and a small developer team. Should they start with: "
                        "1. Simple prompt-based chatbot 2. RAG chatbot 3. Fine-tuning "
                        "4. Agent with tools. Give a practical recommendation with trade-offs."
                    ),
                )
                reason_model = gr.Dropdown(
                    REASONING_MODELS,
                    label="Model",
                    value="gpt-5.5",
                )
                reasoning_effort = gr.Radio(
                    ["low", "medium", "high"],
                    label="Reasoning Effort",
                    value="medium",
                )
                max_output_tokens_reason = gr.Slider(
                    minimum=100,
                    maximum=8000,
                    step=50,
                    value=900,
                    label="Max Output Tokens",
                )
                show_settings_reason = gr.Checkbox(value=True, label="Show Settings")
                reason_button = gr.Button("Reason", variant="primary")

            with gr.Column(scale=1):
                reason_output = gr.Textbox(
                    lines=22,
                    label="Output",
                    elem_classes=["output-box"],
                    show_copy_button=True,
                )

        reason_button.click(
            fn=run_reasoning,
            inputs=[
                reason_prompt,
                reason_model,
                reasoning_effort,
                max_output_tokens_reason,
                show_settings_reason,
            ],
            outputs=reason_output,
        )


if __name__ == "__main__":
    demo.queue()
    demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.getenv("PORT", "7860")),
    )