OrganizingForChange commited on
Commit
9e73d96
·
verified ·
1 Parent(s): 79eb28b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -40
app.py CHANGED
@@ -84,16 +84,8 @@ def compose_system_prompt(targets, additional_sysinfo, feedback, user_message, r
84
  return prompt.strip()
85
 
86
  def split_main_and_feedback(llm_output):
87
- """
88
- Splits the LLM output at the first appearance of a divider line.
89
- Supports both classic '---' (3+ hyphens) and Unicode dash lines (em/en/horizontal bar).
90
- """
91
  import re
92
- # Match a line that consists only of dash-like characters (with optional surrounding whitespace)
93
- # - {3,} ensures at least 3 ASCII hyphens (classic markdown rule)
94
- # [—–―]+ matches one or more of em dash, en dash, or horizontal bar
95
  pattern = re.compile(r'^(?:\s*)(?:-{3,}|[—–―]+)(?:\s*)$', flags=re.MULTILINE)
96
-
97
  m = pattern.search(llm_output or "")
98
  if m:
99
  main_message = llm_output[:m.start()].strip()
@@ -102,9 +94,13 @@ def split_main_and_feedback(llm_output):
102
  main_message = (llm_output or "").strip()
103
  feedback_message = ""
104
  return main_message, feedback_message
105
-
 
 
 
106
  def run_llm(
107
- api_key, targets, additional_sysinfo, user_message, region, model, reasoning_effort, verbosity
 
108
  ):
109
  feedback = True # ALWAYS ENABLED
110
 
@@ -123,12 +119,27 @@ def run_llm(
123
  ]
124
 
125
  try:
126
- resp = client.responses.create(
127
- model=model, # e.g., "gpt-5", "gpt-5-mini", "gpt-5-nano"
128
- input=messages,
129
- reasoning={"effort": reasoning_effort}, # "minimal" | "low" | "medium" | "high"
130
- text={"verbosity": verbosity} # "low" | "medium" | "high"
131
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  full_content = (getattr(resp, "output_text", None) or "").strip()
134
  if not full_content:
@@ -157,7 +168,12 @@ def run_llm(
157
  return f"An error occurred: {e}", "", ""
158
 
159
  target_options = get_target_options()
160
- model_choices = ["gpt-5","gpt-5-mini"]
 
 
 
 
 
161
 
162
  custom_css = """
163
  /* Apply to both textarea and contenteditable fallback /
@@ -209,7 +225,7 @@ with gr.Blocks(css=custom_css) as demo:
209
  with gr.Column(scale=2):
210
  gr.Markdown("""
211
  ## Experimental LLM Segment Messaging App
212
- This tool helps you improve, adapt, and review your written messaging—emails, newsletters, petitions, announcements, and more—using a state-of-the-art AI language model. It is based on the excellent research on segmentation by [EcoAnalytics](https://ecoanalyticscanada.org/).
213
 
214
  You can select your intended audiences (choose multiple if needed!), add optional instructions for the AI, and receive an output that is tailored for clarity, effectiveness, and your communication goal.
215
 
@@ -219,7 +235,7 @@ When you are ready, just hit the "Generate Targetted Message" button and wait a
219
 
220
  This tool is “expert adjacent”—it is designed to support people with some experience in communications work, not to generate communications materials from scratch.
221
 
222
- This tool was created by [Organizing for Change](https://www.organizingforchange.org). For support, contact Sebastian at sebastian@organizingforchange.org.
223
  """)
224
  with gr.Column(scale=1):
225
  gr.Image(
@@ -237,25 +253,43 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
237
  with gr.Row():
238
  with gr.Column():
239
  model = gr.Dropdown(
240
- choices=model_choices,
241
- value="gpt-5", # default to GPT-5
242
- label="OpenAI Model",
243
- info="Select the model to use."
244
- )
245
  with gr.Column():
246
  reasoning_effort = gr.Dropdown(
247
- choices=["minimal", "low", "medium", "high"],
248
- value="medium",
249
- label="Reasoning Effort",
250
- info="How hard the model thinks and how willingly it calls tools"
251
- )
 
252
  with gr.Column():
253
  verbosity = gr.Dropdown(
254
- choices=["low", "medium", "high"],
255
- value="medium",
256
- label="Verbosity",
257
- info="Whether answers are short and to the point or long and comprehensive (impacts feedback section most)"
258
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  with gr.Row():
260
  api_key = gr.Textbox(
261
  type="password",
@@ -278,13 +312,12 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
278
  )
279
  with gr.Row():
280
  target = gr.Checkboxgroup(
281
- choices=target_options,
282
  label="Target Audience Segments",
283
  info="Select one or more intended audience segments. Your message will be adapted for all selected groups together.",
284
- value=[] # default: nothing checked
285
  )
286
 
287
- ### --- (Optional) System Prompt Injection ---
288
  with gr.Accordion("Advanced: System Prompt Injection (optional)", open=False):
289
  additional_sysinfo = gr.Textbox(
290
  lines=3,
@@ -293,9 +326,7 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
293
  info="Use this to inject additional instructions to the system prompt.",
294
  show_label=False
295
  )
296
-
297
 
298
- ### --- Communications Copy to be Retargetted ---
299
  with gr.Group():
300
  user_message = gr.Textbox(
301
  lines=10,
@@ -336,10 +367,36 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
336
  info="See <a href='https://platform.openai.com/docs/pricing' target='_blank'>OpenAI pricing details</a> and <a href='https://epoch.ai/gradient-updates/how-much-energy-does-chatgpt-use' target='_blank'>How much energy does ChatGPT use?</a> for information about token cost and energy usage"
337
  )
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  # --- Connect submit button after outputs are created ---
340
  submit.click(
341
  fn=run_llm,
342
- inputs=[api_key, target, additional_sysinfo, user_message, region, model, reasoning_effort, verbosity],
 
 
 
343
  outputs=[output, feedback_box, token_count_box]
344
  )
345
 
 
84
  return prompt.strip()
85
 
86
  def split_main_and_feedback(llm_output):
 
 
 
 
87
  import re
 
 
 
88
  pattern = re.compile(r'^(?:\s*)(?:-{3,}|[—–―]+)(?:\s*)$', flags=re.MULTILINE)
 
89
  m = pattern.search(llm_output or "")
90
  if m:
91
  main_message = llm_output[:m.start()].strip()
 
94
  main_message = (llm_output or "").strip()
95
  feedback_message = ""
96
  return main_message, feedback_message
97
+
98
+ def is_gpt5_model(model_name: str) -> bool:
99
+ return bool(model_name and model_name.startswith("gpt-5"))
100
+
101
  def run_llm(
102
+ api_key, targets, additional_sysinfo, user_message, region,
103
+ model, reasoning_effort, verbosity, temperature, top_p
104
  ):
105
  feedback = True # ALWAYS ENABLED
106
 
 
119
  ]
120
 
121
  try:
122
+ req = {
123
+ "model": model,
124
+ "input": messages
125
+ }
126
+
127
+ # Route parameters based on model family
128
+ if is_gpt5_model(model):
129
+ # gpt-5 family: use "reasoning" and "text" options
130
+ req["reasoning"] = {"effort": reasoning_effort} if reasoning_effort else None
131
+ req["text"] = {"verbosity": verbosity} if verbosity else None
132
+ else:
133
+ # gpt-4 family: use temperature/top_p
134
+ if temperature is not None:
135
+ req["temperature"] = float(temperature)
136
+ if top_p is not None:
137
+ req["top_p"] = float(top_p)
138
+
139
+ # Remove any None entries so we don't send them
140
+ req = {k: v for k, v in req.items() if v is not None}
141
+
142
+ resp = client.responses.create(**req)
143
 
144
  full_content = (getattr(resp, "output_text", None) or "").strip()
145
  if not full_content:
 
168
  return f"An error occurred: {e}", "", ""
169
 
170
  target_options = get_target_options()
171
+
172
+ # Add gpt-4 models alongside gpt-5
173
+ model_choices = [
174
+ "gpt-5", "gpt-5-mini",
175
+ "gpt-4o", "gpt-4-turbo"
176
+ ]
177
 
178
  custom_css = """
179
  /* Apply to both textarea and contenteditable fallback /
 
225
  with gr.Column(scale=2):
226
  gr.Markdown("""
227
  ## Experimental LLM Segment Messaging App
228
+ This tool helps you improve, adapt, and review your written messaging—emails, newsletters, petitions, announcements, and more—using a state-of-the-art AI language model. It is based on the excellent research on segmentation by EcoAnalytics.
229
 
230
  You can select your intended audiences (choose multiple if needed!), add optional instructions for the AI, and receive an output that is tailored for clarity, effectiveness, and your communication goal.
231
 
 
235
 
236
  This tool is “expert adjacent”—it is designed to support people with some experience in communications work, not to generate communications materials from scratch.
237
 
238
+ This tool was created by Organizing for Change. For support, contact Sebastian at sebastian@organizingforchange.org.
239
  """)
240
  with gr.Column(scale=1):
241
  gr.Image(
 
253
  with gr.Row():
254
  with gr.Column():
255
  model = gr.Dropdown(
256
+ choices=model_choices,
257
+ value="gpt-5",
258
+ label="OpenAI Model",
259
+ info="Select the model to use."
260
+ )
261
  with gr.Column():
262
  reasoning_effort = gr.Dropdown(
263
+ choices=["minimal", "low", "medium", "high"],
264
+ value="medium",
265
+ label="Reasoning Effort (gpt-5 only)",
266
+ info="How hard the model thinks and how willingly it calls tools",
267
+ visible=True # default visible for gpt-5
268
+ )
269
  with gr.Column():
270
  verbosity = gr.Dropdown(
271
+ choices=["low", "medium", "high"],
272
+ value="medium",
273
+ label="Verbosity (gpt-5 only)",
274
+ info="Whether answers are short and to the point or long and comprehensive (impacts feedback section most)",
275
+ visible=True # default visible for gpt-5
276
+ )
277
+ # Sliders shown for gpt-4 family only
278
+ with gr.Row():
279
+ with gr.Column():
280
+ temperature = gr.Slider(
281
+ minimum=0.0, maximum=2.0, value=0.7, step=0.05,
282
+ label="Temperature (gpt-4 only)",
283
+ info="Higher is more random/creative; lower is more focused",
284
+ visible=False # hidden for gpt-5 default
285
+ )
286
+ with gr.Column():
287
+ top_p = gr.Slider(
288
+ minimum=0.0, maximum=1.0, value=1.0, step=0.01,
289
+ label="Top-p (gpt-4 only)",
290
+ info="Nucleus sampling; consider reducing if increasing temperature",
291
+ visible=False # hidden for gpt-5 default
292
+ )
293
  with gr.Row():
294
  api_key = gr.Textbox(
295
  type="password",
 
312
  )
313
  with gr.Row():
314
  target = gr.Checkboxgroup(
315
+ choices=get_target_options(),
316
  label="Target Audience Segments",
317
  info="Select one or more intended audience segments. Your message will be adapted for all selected groups together.",
318
+ value=[]
319
  )
320
 
 
321
  with gr.Accordion("Advanced: System Prompt Injection (optional)", open=False):
322
  additional_sysinfo = gr.Textbox(
323
  lines=3,
 
326
  info="Use this to inject additional instructions to the system prompt.",
327
  show_label=False
328
  )
 
329
 
 
330
  with gr.Group():
331
  user_message = gr.Textbox(
332
  lines=10,
 
367
  info="See <a href='https://platform.openai.com/docs/pricing' target='_blank'>OpenAI pricing details</a> and <a href='https://epoch.ai/gradient-updates/how-much-energy-does-chatgpt-use' target='_blank'>How much energy does ChatGPT use?</a> for information about token cost and energy usage"
368
  )
369
 
370
+ # Dynamic UI: toggle fields on model change
371
+ def on_model_change(selected_model):
372
+ if is_gpt5_model(selected_model):
373
+ return (
374
+ gr.update(visible=True), # reasoning_effort
375
+ gr.update(visible=True), # verbosity
376
+ gr.update(visible=False), # temperature
377
+ gr.update(visible=False), # top_p
378
+ )
379
+ else:
380
+ return (
381
+ gr.update(visible=False), # reasoning_effort
382
+ gr.update(visible=False), # verbosity
383
+ gr.update(visible=True), # temperature
384
+ gr.update(visible=True), # top_p
385
+ )
386
+
387
+ model.change(
388
+ fn=on_model_change,
389
+ inputs=model,
390
+ outputs=[reasoning_effort, verbosity, temperature, top_p]
391
+ )
392
+
393
  # --- Connect submit button after outputs are created ---
394
  submit.click(
395
  fn=run_llm,
396
+ inputs=[
397
+ api_key, target, additional_sysinfo, user_message, region,
398
+ model, reasoning_effort, verbosity, temperature, top_p
399
+ ],
400
  outputs=[output, feedback_box, token_count_box]
401
  )
402