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
 
 
 
 
 
 
 
 
 
 
 
 
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import os
import json
from typing import Optional, Dict, List
from pydantic import BaseModel, Field, ValidationError
from huggingface_hub import InferenceClient
from huggingface_hub.errors import HfHubHTTPError
import gradio as gr

# Define Pydantic models for input and output
class PromptInput(BaseModel):
  text: str = Field(..., description="The initial prompt text")
  meta_prompt_choice: str = Field(..., description="Choice of meta prompt strategy")

class LLMRequest(BaseModel):
  model: str
  messages: List[Dict[str, str]]
  max_tokens: int = 2000
  temperature: float = 0.8

class LLMResponseChoice(BaseModel):
  message: Dict[str, str]

class LLMResponse(BaseModel):
  choices: List[LLMResponseChoice]

class RefinementOutput(BaseModel):
  initial_prompt_evaluation: Optional[str] = None
  refined_prompt: Optional[str] = None
  explanation_of_refinements: Optional[str] = None
  response_content: Optional[str] = None

class PromptRefiner:
  def __init__(self, api_token: str):
      self.client = InferenceClient(token=api_token, timeout=300)
      self.meta_prompts = {
          "morphosis": original_meta_prompt,
          "verse": new_meta_prompt,
          "physics": metaprompt1,
          "bolism": loic_metaprompt,
          "done": metadone,
          "star": echo_prompt_refiner,
          "math": math_meta_prompt,
          "arpe": autoregressive_metaprompt
      }

  def refine_prompt(self, prompt_input: PromptInput) -> tuple:
      try:
          selected_meta_prompt = self.meta_prompts.get(prompt_input.meta_prompt_choice, advanced_meta_prompt)
          messages = [
              {"role": "system", "content": 'You are an expert at refining and extending prompts. Given a basic prompt, provide a more detailed.'},
              {"role": "user", "content": selected_meta_prompt.replace("[Insert initial prompt here]", prompt_input.text)}
          ]

          request_data = LLMRequest(
              model=prompt_refiner_model,
              messages=messages
          )

          response = self.client.chat_completion(**request_data.dict())
          response_data = LLMResponse(**response)

          # Extract the content from the response
          response_content = response_data.choices[0].message['content'].strip()

          # Parse the response content using Pydantic
          result = self._parse_response_content(response_content)

          return (
              result.initial_prompt_evaluation,
              result.refined_prompt,
              result.explanation_of_refinements,
              result.dict()
          )

      except (HfHubHTTPError, ValidationError) as e:
          return (
              f"Error: {str(e)}",
              "The selected model is currently experiencing high traffic.",
              "The selected model is currently experiencing high traffic.",
              {}
          )
      except Exception as e:
          return (
              f"Error: {str(e)}",
              "",
              "An unexpected error occurred.",
              {}
          )

  def _parse_response_content(self, response_content: str) -> RefinementOutput:
      try:
          # Assume the response content is a valid JSON string
          response_dict = json.loads(response_content)
          return RefinementOutput(**response_dict)
      except (json.JSONDecodeError, ValidationError) as e:
          print(f"Error parsing response: {e}")
          print(f"Raw content: {response_content}")
          return RefinementOutput(
              initial_prompt_evaluation="Error parsing response",
              explanation_of_refinements=str(e),
              response_content=response_content
          )

  def apply_prompt(self, prompt: str, model: str) -> str:
      try:
          messages = [
              {"role": "system", "content": "You are a helpful assistant. Answer in stylized version with latex format or markdown if relevant. Separate your answer into logical sections using level 2 headers (##) for sections and bolding (**) for subsections. Incorporate a variety of lists, headers, and text to make the answer visually appealing"},
              {"role": "user", "content": prompt}
          ]

          request_data = LLMRequest(
              model=model,
              messages=messages
          )

          response = self.client.chat_completion(**request_data.dict())
          response_data = LLMResponse(**response)
          output = response_data.choices[0].message['content'].strip()
          return output.replace('\n\n', '\n').strip()

      except Exception as e:
          return f"Error: {str(e)}"

class GradioInterface:
  def __init__(self, prompt_refiner: PromptRefiner):
      self.prompt_refiner = prompt_refiner
      custom_css = """
      .container {
          border: 2px solid #2196F3;
          border-radius: 10px;
          padding: 12px;
          margin: 6px;
          background: white;
          position: relative;
          width: 100% !important;
          max-width: 1200px !important;
          margin: 0 auto 20px auto !important;
      }

      .container::before {
          position: absolute;
          top: -10px;
          left: 20px;
          background: white;
          padding: 0 10px;
          color: #2196F3;
          font-weight: bold;
          font-size: 1.2em;
      }

      .title-container {
          width: fit-content !important;
          margin: 0 auto !important;
          padding: 2px 40px !important;
          border: 1px solid #0066cc !important;
          border-radius: 10px !important;
          background-color: rgba(0, 102, 204, 0.05) !important;
      }

      .title-container * {
          text-align: center;
          margin: 0 !important;
          line-height: 1.2 !important;
      }

      .title-container h1 {
          font-size: 28px !important;
          margin-bottom: 1px !important;
      }

      .title-container h3 {
          font-size: 18px !important;
          margin-bottom: 1px !important;
      }

      .title-container p {
          font-size: 14px !important;
          margin-bottom: 1px !important;
      }

      .input-container::before { 
          content: 'PROMPT REFINEMENT';
      }

      .analysis-container::before {
          content: 'ANALYSIS';
      }

      .model-container::before {
          content: 'MODEL APPLICATION';
      }

      .examples-container::before {
          content: 'EXAMPLES';
      }

      /* Resizable textbox */
      .input-container textarea {
          resize: vertical !important;
          min-height: 100px !important;
          max-height: 500px !important;
          width: 100% !important;
          border: 1px solid #ddd !important;
          border-radius: 4px !important;
          padding: 8px !important;
          transition: all 0.3s ease !important;
      }

      .input-container textarea:focus {
          border-color: #2196F3 !important;
          box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1) !important;
      }

      /* Radio group styling */
      .radio-group {
          background-color: rgba(0, 102, 204, 0.05) !important;
          padding: 10px !important;
          border-radius: 8px !important;
          border: 1px solid rgba(0, 102, 204, 0.1) !important;
          display: flex !important;
          justify-content: center !important;
          flex-wrap: wrap !important;
          gap: 8px !important;
          width: 100% !important;
      }

      .gradio-radio {
          display: flex !important;
          justify-content: center !important;
          flex-wrap: wrap !important;
          gap: 8px !important;
      }

      .gradio-radio label {
          display: flex !important;
          align-items: center !important;
          padding: 6px 12px !important;
          border: 1px solid #ddd !important;
          border-radius: 4px !important;
          cursor: pointer !important;
          background: white !important;
          margin: 4px !important;
      }

      .gradio-radio input[type="radio"]:checked + label {
          background: rgba(0, 102, 204, 0.1) !important;
          border-color: #0066cc !important;
          color: #0066cc !important;
          font-weight: bold !important;
      }

      /* Button styling */
      .gradio-button {
          background-color: white !important;
          color: #2196F3 !important;
          border: 2px solid #2196F3 !important;
          border-radius: 4px !important;
          padding: 8px 16px !important;
          margin: 10px 0 !important;
          font-weight: bold !important;
          transition: all 0.3s ease !important;
      }

      .gradio-button:hover {
          background-color: #2196F3 !important;
          color: white !important;
          box-shadow: 0 2px 5px rgba(33, 150, 243, 0.3) !important;
      }

      /* Accordion styling */
      .gradio-accordion {
          margin: 10px 0 !important;
          border: none !important;
      }

      /* Container alignment */
      .gradio-container {
          display: flex !important;
          flex-direction: column !important;
          align-items: center !important;
          width: 100% !important;
          max-width: 1200px !important;
          margin: 0 auto !important;
      }

      /* Dropdown styling */
      .gradio-dropdown {
          width: 100% !important;
          max-width: 300px !important;
      }

      /* JSON container */
      .full-response-json {
          margin-top: 20px !important;
          padding: 10px !important;
          background-color: rgba(0, 102, 204, 0.05) !important;
          border-radius: 8px !important;
      }
      """

      with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as self.interface:
          with gr.Column(elem_classes=["container", "title-container"]):
              gr.Markdown("# PROMPT++")
              gr.Markdown("### Automating Prompt Engineering by Refining your Prompts")
              gr.Markdown("Learn how to generate an improved version of your prompts.")

          with gr.Column(elem_classes=["container", "input-container"]):
              prompt_text = gr.Textbox(
                  label="Type your prompt (or let it empty to see metaprompt)",
                  lines=5
              )
              meta_prompt_choice = gr.Radio(
                  ["star", "done", "physics", "morphosis", "verse", "phor", "bolism", "math", "arpe"],
                  label="Choose Meta Prompt",
                  value="star",
                  elem_classes=["no-background", "radio-group"]
              )
              refine_button = gr.Button("Refine Prompt")

              with gr.Row(elem_classes=["container2"]):
                  with gr.Accordion("Examples", open=False):
                      gr.Examples(
                          examples=[
                              ["Write a story on the end of prompt engineering replaced by an Ai specialized in refining prompts.", "star"],
                              ["Tell me about that guy who invented the light bulb", "physics"],
                              ["Explain the universe.", "star"],
                              ["What's the population of New York City and how tall is the Empire State Building and who was the first mayor?", "morphosis"],
                              ["List American presidents.", "verse"],
                              ["Explain why the experiment failed.", "morphosis"],
                              ["Is nuclear energy good?", "verse"],
                              ["How does a computer work?", "phor"],
                              ["How to make money fast?", "done"],
                              ["how can you prove IT0's lemma in stochastic calculus ?", "arpe"],
                          ],
                          inputs=[prompt_text, meta_prompt_choice]
                      )

                  with gr.Accordion("Meta Prompt explanation", open=False):
                      gr.Markdown(explanation_markdown)

          with gr.Column(elem_classes=["container", "analysis-container"]):
              gr.Markdown(' ')
              gr.Markdown("### Initial prompt analysis")
              analysis_evaluation = gr.Markdown()
              gr.Markdown("### Refined Prompt")
              refined_prompt = gr.Textbox(
                  label="Refined Prompt",
                  interactive=True,
                  show_label=True,
                  show_copy_button=True
              )
              gr.Markdown("### Explanation of Refinements")
              explanation_of_refinements = gr.Markdown()

          with gr.Column(elem_classes=["container", "model-container"]):
              with gr.Row():
                  apply_model = gr.Dropdown(models,
                                            value="meta-llama/Llama-3.1-8B-Instruct",
                                            label="Choose the Model",
                                            container=False,
                                            scale=1,
                                            min_width=300
                                            )
                  apply_button = gr.Button("Apply MetaPrompt")

              gr.Markdown("### Prompts on chosen model")
              with gr.Tabs():
                  with gr.TabItem("Original Prompt Output"):
                      original_output = gr.Markdown()
                  with gr.TabItem("Refined Prompt Output"):
                      refined_output = gr.Markdown()
          with gr.Accordion("Full Response JSON", open=False, visible=True):
              full_response_json = gr.JSON()

          refine_button.click(
              fn=self.refine_prompt,
              inputs=[prompt_text, meta_prompt_choice],
              outputs=[analysis_evaluation, refined_prompt, explanation_of_refinements, full_response_json]
          )

          apply_button.click(
              fn=self.apply_prompts,
              inputs=[prompt_text, refined_prompt, apply_model],
              outputs=[original_output, refined_output]
          )

  def refine_prompt(self, prompt: str, meta_prompt_choice: str) -> tuple:
      try:
          input_data = PromptInput(text=prompt, meta_prompt_choice=meta_prompt_choice)
          initial_prompt_evaluation, refined_prompt, explanation_refinements, full_response = self.prompt_refiner.refine_prompt(input_data)

          analysis_evaluation = f"\n\n{initial_prompt_evaluation}"
          return (
              analysis_evaluation,
              refined_prompt,
              explanation_refinements,
              full_response
          )
      except ValidationError as e:
          return (
              f"Validation Error: {str(e)}",
              "",
              "",
              {}
          )

  def apply_prompts(self, original_prompt: str, refined_prompt: str, model: str):
      original_output = self.prompt_refiner.apply_prompt(original_prompt, model)
      refined_output = self.prompt_refiner.apply_prompt(refined_prompt, model)
      return original_output, refined_output

  def launch(self, share=False):
      self.interface.launch(share=share)

metaprompt_explanations = {
  "star": "Use ECHO when you need a comprehensive, multi-stage approach for complex prompts. It's ideal for tasks requiring in-depth analysis, exploration of multiple alternatives, and synthesis of ideas. Choose this over others when you have time for a thorough refinement process and need to consider various aspects of the prompt.",
  "done": "Opt for this when you want a structured approach with emphasis on role-playing and advanced techniques. It's particularly useful for tasks that benefit from diverse perspectives and complex reasoning. Prefer this over 'physics' when you need a more detailed, step-by-step refinement process.",
  "physics": "Select this when you need a balance between structure and advanced techniques, with a focus on role-playing. It's similar to 'done' but may be more suitable for scientific or technical prompts. Choose this over 'done' for a slightly less complex approach.",
  "morphosis": "Use this simplified approach for straightforward prompts or when time is limited. It focuses on essential improvements without complex techniques. Prefer this over other methods when you need quick, clear refinements without extensive analysis.",
  "verse": "Choose this method when you need to analyze and improve a prompt's strengths and weaknesses, with a focus on information flow. It's particularly useful for enhancing the logical structure of prompts. Use this over 'morphosis' when you need more depth but less complexity than 'star'.",
  "phor": "Employ this advanced approach when you need to combine multiple prompt engineering techniques. It's ideal for complex tasks requiring both clarity and sophisticated prompting methods. Select this over 'star' when you want a more flexible, technique-focused approach.",
  "bolism": "Utilize this method when working with autoregressive language models and when the task requires careful reasoning before conclusions. It's best for prompts that need detailed output formatting. Choose this over others when the prompt's structure and reasoning order are crucial."
}

models = [
  "meta-llama/Meta-Llama-3-70B-Instruct",
  "meta-llama/Meta-Llama-3-8B-Instruct",
  "meta-llama/Llama-3.1-70B-Instruct",
  "meta-llama/Llama-3.1-8B-Instruct",
  "meta-llama/Llama-3.2-3B-Instruct",
  "meta-llama/Llama-3.2-1B-Instruct",
  "meta-llama/Llama-2-13b-chat-hf",
  "meta-llama/Llama-2-7b-chat-hf",
  "HuggingFaceH4/zephyr-7b-beta",
  "HuggingFaceH4/zephyr-7b-alpha",
  "Qwen/Qwen2.5-72B-Instruct",
  "Qwen/Qwen2.5-1.5B",
  "google/gemma-1.1-2b-it"
]

explanation_markdown = "".join([f"- **{key}**: {value}\n" for key, value in metaprompt_explanations.items()])

if __name__ == '__main__':
  api_token = os.getenv('HF_API_TOKEN')
  if not api_token:
      raise ValueError("HF_API_TOKEN not found in environment variables")

  # Load environment variables for meta prompts
  metadone = os.getenv('metadone')
  prompt_refiner_model = os.getenv('prompt_refiner_model')
  echo_prompt_refiner = os.getenv('echo_prompt_refiner')
  metaprompt1 = os.getenv('metaprompt1')
  loic_metaprompt = os.getenv('loic_metaprompt')
  original_meta_prompt = os.getenv('original_meta_prompt')
  new_meta_prompt = os.getenv('new_meta_prompt')
  advanced_meta_prompt = os.getenv('advanced_meta_prompt')
  math_meta_prompt = os.getenv('metamath')
  autoregressive_metaprompt = os.getenv('autoregressive_metaprompt')

  prompt_refiner = PromptRefiner(api_token)
  gradio_interface = GradioInterface(prompt_refiner)
  gradio_interface.launch(share=True)