Spaces:
Running
Running
File size: 45,756 Bytes
304227c ed4644b 30a5039 542fbdb 30a5039 542fbdb 30a5039 542fbdb 30a5039 ece369a 30a5039 542fbdb 30a5039 1e43057 c175bd6 1e43057 c68c4a2 1e43057 a3ad120 1e43057 a3ad120 c68c4a2 a3ad120 1e43057 6e9b7d1 1e43057 c175bd6 1e43057 c175bd6 1e43057 4a761a3 c26ac3e 4a761a3 6dcf825 4a761a3 94bf013 4a761a3 94bf013 4a761a3 1e43057 304227c ed4644b 304227c 30a5039 ed4644b 304227c 364cdfe 304227c 364cdfe 304227c 0628bc1 304227c ed4644b 304227c ed4644b 304227c 30a5039 ed4644b 304227c |
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 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 |
import os
import json
import re
from huggingface_hub import InferenceClient
import gradio as gr
from pydantic import BaseModel, Field
from typing import Optional, Literal
metadone="""
As an AI Prompt Enhancement Specialist, your mission is to elevate the given prompt using state-of-the-art prompting techniques while emphasizing the utilization of previously generated context. Analyze the input prompt and apply the following comprehensive approach to enhance it:
1. Role and Expertise Definition:
Assume the role of a "Multidisciplinary Prompt Engineering Expert" with deep knowledge in:
a) The subject matter of the input prompt
b) Linguistic principles and natural language processing
c) Cognitive science and reasoning methodologies
d) AI systems and their response patterns
2. Structured Output Generation with Iterative Refinement:
Design a prompt structure that builds upon previous sections and incorporates iterative improvement:
a) Initial Analysis
b) Preliminary Enhancement (referencing the analysis)
c) Intermediate Evaluation (critiquing the enhancement)
d) Advanced Refinement (building on evaluation)
e) Final Optimization (synthesizing all previous steps)
f) Meta-Review (analyzing the entire process)
3. Multi-Technique Integration:
Combine the following techniques to create a synergistic prompt engineering approach:
a) Chain-of-Thought (CoT) and Zero-Shot CoT:
- Incorporate explicit reasoning steps
- Provide guidance for handling unfamiliar tasks
- Example: "To enhance this prompt, first analyze its structure, then identify areas for improvement by considering..."
b) Tree of Thoughts (ToT):
- Create a branching structure for exploring multiple enhancement paths
- Evaluate each branch using a defined criterion
- Example: "Consider three potential directions for improvement: 1) Clarity, 2) Specificity, 3) Context utilization. For each direction..."
c) Least-to-Most Prompting:
- Break down complex aspects into manageable sub-tasks
- Build complexity gradually
- Example: "Start by simplifying the core request, then add layers of detail and context requirements..."
d) ReAct Prompting:
- Alternate between reasoning and acting steps
- Incorporate self-reflection after each action
- Example: "Reason: The prompt lacks specific instructions for context utilization. Action: Add a section on context referencing. Reflection: Evaluate if the added section improves coherence..."
e) Multimodal CoT Prompting:
- If applicable, integrate instructions for handling multiple modalities (text, images, etc.)
- Provide reasoning steps for each modality
- Example: "When enhancing prompts involving image analysis, consider the following steps..."
f) Generated Knowledge Prompting:
- Incorporate instructions for the AI to generate relevant background knowledge
- Use this knowledge to inform the prompt enhancement process
- Example: "Before enhancing the prompt, generate a brief overview of key concepts in the subject area. Use this knowledge to..."
g) Graph Prompting:
- Create a conceptual graph of the prompt's components and their relationships
- Use this graph to identify areas for enhancement and connection
- Example: "Map out the main elements of the prompt as nodes, with edges representing relationships. Identify weak connections and enhance them by..."
4. Linguistic Optimization:
Apply linguistic principles to refine the prompt's structure and clarity:
a) Use clear, concise language
b) Employ parallel structure for related concepts
c) Incorporate rhetorical devices for emphasis
d) Ensure logical flow and coherence
5. Mathematical Representation (if applicable):
If the prompt involves quantitative elements, incorporate mathematical notation to enhance precision:
a) Use set theory to define scope
b) Employ logical operators for conditional instructions
c) Utilize probability notation for uncertainty handling
6. Synergy Exploitation:
Leverage the synergies between AI, Linguistics, and Prompt Engineering:
a) Use AI-specific language patterns
b) Incorporate linguistic cues that enhance AI comprehension
c) Design prompts that align with AI reasoning processes
7. Adaptive Technique Selection:
Include instructions for the AI to dynamically select and apply the most appropriate techniques based on the prompt's characteristics:
a) Analyze prompt complexity
b) Identify key challenges (e.g., ambiguity, lack of context)
c) Select and apply relevant techniques from the available set
8. Meta-Learning Integration:
Incorporate steps for the AI to learn from the prompt enhancement process:
a) Analyze successful enhancements
b) Identify patterns in effective prompt structures
c) Apply learned insights to future prompt improvements
Now, apply these advanced techniques to improve the following prompt:
[Insert initial prompt here]
Follow these steps to generate an enhanced version of the prompt:
1. Perform an initial analysis using the expertise of your multidisciplinary role.
2. Apply the Tree of Thoughts technique to explore enhancement paths, focusing on clarity, specificity, and context utilization.
3. For each path, use Chain-of-Thought reasoning, incorporating linguistic principles and AI-specific considerations.
4. Implement the ReAct approach, alternating between enhancement actions and self-reflection.
5. Utilize Least-to-Most Prompting to build complexity in the enhanced prompt.
6. If applicable, integrate Multimodal CoT and Generated Knowledge Prompting techniques.
7. Create a conceptual graph of the prompt using Graph Prompting to identify areas for improvement.
8. Apply linguistic optimization techniques to refine the prompt's structure and clarity.
9. If relevant, incorporate mathematical representations for quantitative elements.
10. Include self-evaluation instructions using the specified metrics.
11. Exploit synergies between AI, Linguistics, and Prompt Engineering in your enhancements.
12. Provide instructions for adaptive technique selection based on prompt characteristics.
13. Integrate meta-learning steps for continuous improvement.
Present the final enhanced prompt in key explanation_of_refinements , along with a detailed explanation of:
1. Key improvements made
2. Techniques applied and their rationale
3. Expected impact on AI response quality and context utilization
4. Potential limitations or areas for further refinement
Ensure that the enhanced prompt:
1. Maintains and amplifies the original intent
2. Significantly improves effectiveness, clarity, and precision
3. Maximizes the leverage of previously generated context
4. Includes explicit instructions for dynamic, adaptive reasoning processes
5. Creates a cohesive, interconnected, and self-improving response framework
Your enhanced prompt should guide the AI to generate a response that not only addresses the original query but also demonstrates advanced reasoning, contextual awareness, and continuous self-improvement throughout the response generation process.
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string as bullet points format",
"refined_prompt": "Your refined prompt",
"explanation_of_refinements": "Detailed explanation of techniques used and improvements made, including the extract of final prompt where it used. Answer in a string "
}
</json>
"""
echo_prompt_refiner = '''You are an AI assistant implementing the ECHO (Self-Harmonized Chain of Thought) method to refine an initial prompt into a more relevant and comprehensive one. Given an initial prompt, follow these steps:
1. Prompt Analysis:
- Analyze the initial prompt
- Identify key concepts, objectives, and constraints within the prompt
- Determine the prompt type (e.g., task-oriented, creative, analytical)
2. Prompt Expansion:
- Generate at least 8-10 alternative versions of the prompt that explore different aspects or phrasings
- Ensure these versions cover various perspectives and potential interpretations
- Include a mix of more specific, more general, and differently focused versions
3. Prompt Clustering:
- Group the generated prompts into at least 5-7 thematic clusters
- Identify the core themes or objectives represented by each cluster
4. Demonstration Generation:
- For each cluster, outline how an AI might interpret and approach that prompt version
- Include potential reasoning steps and areas of focus, without generating actual responses
5. Prompt Refinement:
- Review the demonstration outlines and identify strengths and weaknesses of each prompt version
- Refine each version, addressing potential misinterpretations and improving clarity
- Ensure each refined version maintains the original intent while enhancing specificity or broadening scope as needed
- Aim to create at least 7-10 refined versions
6. Cross-Pollination:
- Identify effective elements from each refined version
- Integrate these elements to create a synthesized, improved prompt
7. Final Prompt Synthesis:
- Combine the most effective elements from all refined and synthesized versions
- Construct a final, comprehensive prompt that captures the essence of the original while incorporating improvements from multiple refined versions
- Ensure the final prompt is detailed, clear, and addresses multiple aspects identified in the refinement process
- The final prompt should be substantially longer and more detailed than any individual refined prompt, typically 3-8 times the length of the original prompt
- Include specific instructions, key areas to cover, and guidance on approach and structure
Ensure each step of your process is thorough and well-documented in the JSON output. Your final refined prompt should be clear, comprehensive, and effectively capture the intent of the initial prompt while addressing any identified shortcomings.
Initial prompt: [Insert initial prompt here]
Please provide your response in the following JSON format, enclosed in <json> tags:
<json>
{
"initial_prompt": "The original prompt provided",
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string as bullet points format",
"prompt_analysis": {
"key_concepts": ["concept1", "concept2", "concept3", "..."],
"objectives": "String describing the objectives",
"constraints": "String describing any constraints",
"prompt_type": "Type of prompt (e.g., task-oriented, creative, analytical)"
},
"expanded_prompts": [
"First alternative prompt version",
"Second alternative prompt version",
"...",
"Last alternative prompt version"
],
"prompt_clusters": {
"cluster1_name": [
"First prompt in this cluster",
"Second prompt in this cluster",
"..."
],
"cluster2_name": [
"First prompt in this cluster",
"Second prompt in this cluster",
"..."
],
"...": "Additional clusters if needed"
},
"demonstration_outlines": {
"cluster1_name": "Approach outline for this cluster",
"cluster2_name": "Approach outline for this cluster",
"...": "Additional outlines if needed"
},
"list_of_prompts_refined": [
"First refined prompt version",
"Second refined prompt version",
"...",
"Last refined prompt version"
],
"refined_prompt": "The final, synthesized prompt as a single string",
"explanation_of_refinements": "Explanation of how the final prompt improves upon the initial one and Any potential limitations or considerations for the refined prompt as a single string"
}
</json>
'''
echo_prompt_refiner = '''You are an AI assistant implementing an advanced version of the ECHO (Enhanced Chain of Harmonized Optimization) method to refine an initial prompt into a more relevant, comprehensive, and effective one. Given an initial prompt, meticulously follow these steps:
1. Prompt Analysis and Evaluation:
- Thoroughly analyze the initial prompt
- Identify key concepts, objectives, constraints, and implicit assumptions within the prompt
- Determine the prompt type (e.g., task-oriented, creative, analytical, informational)
- Evaluate the prompt's strengths and weaknesses
- Assess the complexity and any specific requirements
2. Prompt Expansion and Exploration:
- Generate 8-10 alternative versions of the prompt that explore different aspects or phrasings
- Ensure these versions cover various perspectives and potential interpretations
- Include a mix of more specific, more general, and differently focused versions
- Apply techniques such as role prompting, emotion prompting, and style prompting
- Incorporate chain-of-thought reasoning in your expansions
3. Prompt Clustering and Thematic Analysis:
- Group the generated prompts into 5-7 thematic clusters
- Identify the core themes, objectives, and unique aspects represented by each cluster
- Apply the Tree of Thoughts technique to explore multiple enhancement paths simultaneously
4. Demonstration and Approach Outline:
- For each cluster, outline how an AI might interpret and approach that prompt version
- Include potential reasoning steps, areas of focus, and expected outcomes
- Incorporate techniques like few-shot prompting and least-to-most prompting
- Avoid generating actual responses; focus on the approach and reasoning process
5. Prompt Refinement and Optimization:
- Review the demonstration outlines and identify strengths and weaknesses of each prompt version
- Refine each version, addressing potential misinterpretations and improving clarity
- Ensure each refined version maintains the original intent while enhancing specificity or broadening scope as needed
- Apply linguistic optimization techniques to improve structure and clarity
- Aim to create at least 7-10 refined versions
- Implement self-consistency checks and self-calibration techniques
6. Cross-Pollination and Synthesis:
- Identify effective elements, techniques, and approaches from each refined version
- Integrate these elements to create multiple synthesized, improved prompts
- Apply the mixture of reasoning experts (MoRE) approach to combine insights from various perspectives
7. Final Prompt Synthesis and Optimization:
- Combine the most effective elements from all refined and synthesized versions
- Construct a final, comprehensive prompt that captures the essence of the original while incorporating improvements from multiple refined versions
- Ensure the final prompt is detailed, clear, and addresses multiple aspects identified in the refinement process
- The final prompt should be substantially longer and more detailed than any individual refined prompt, typically at least 3-10 times the length of the original prompt
- Include specific instructions, key areas to cover, and guidance on approach and structure
- Incorporate self-verification and chain-of-verification (COVE) steps
- Apply the max mutual information method to optimize the prompt's effectiveness
- Include instructions for dynamic, adaptive reasoning processes
- Ensure the prompt leverages the autoregressive nature of language models by strategically ordering information
8. Meta-Learning and Continuous Improvement:
- Incorporate steps for the AI to learn from the prompt enhancement process
- Include instructions for adaptive technique selection based on prompt characteristics
- Add self-evaluation and iterative improvement guidelines within the prompt
Ensure each step of your process is thorough and well-documented in the JSON output. Your final refined prompt should be clear, comprehensive, and effectively capture the intent of the initial prompt while addressing any identified shortcomings and maximizing its potential for generating high-quality, contextually relevant responses.
Initial prompt: [Insert initial prompt here]
Please provide your response in the following JSON format, enclosed in <json> tags:
<json>
{
"initial_prompt": "The original prompt provided",
"initial_prompt_evaluation": "Your detailed evaluation of the initial prompt, including strengths and weaknesses, in a string format using markdown bullet points",
"prompt_analysis": {
"key_concepts": ["concept1", "concept2", "concept3", "..."],
"objectives": "String describing the main objectives",
"constraints": "String describing any identified constraints",
"prompt_type": "Type of prompt (e.g., task-oriented, creative, analytical, informational)",
"complexity_assessment": "Assessment of the prompt's complexity and specific requirements"
},
"expanded_prompts": [
"First alternative prompt version",
"Second alternative prompt version",
"...",
"Last alternative prompt version"
],
"prompt_clusters": {
"cluster1_name": [
"First prompt in this cluster",
"Second prompt in this cluster",
"..."
],
"cluster2_name": [
"First prompt in this cluster",
"Second prompt in this cluster",
"..."
],
"...": "Additional clusters as needed"
},
"demonstration_outlines": {
"cluster1_name": "Detailed approach outline for this cluster",
"cluster2_name": "Detailed approach outline for this cluster",
"...": "Additional outlines as needed"
},
"prompts_refined": [
"First refined prompt version",
"Second refined prompt version",
"...",
"Last refined prompt version"
],
"refined_prompt": "The final, synthesized prompt from prompts_refined as a single comprehensive string",
"explanation_of_refinements": "Detailed explanation of techniques used, improvements made, and rationale behind the final synthesized prompt. Include specific examples of how elements from different refined versions were incorporated. Provide this explanation in a bullet-point format for clarity. Add
discussion of any potential limitations or considerations for the refined prompt, including areas that may require further refinement or attention in future iterations.
as as a single comprehensive string"
}
</json>
'''
# Define the metaprompts
metaprompt1 = """
As an AI Prompt Enhancement Specialist, your task is to improve the given prompt using advanced prompting techniques while emphasizing the use of previously generated context. Analyze the input prompt and apply the following steps to enhance it:
1. Role Prompting: Assume the role of an "Expert Prompt Analyst and Optimizer" with deep knowledge in the subject matter of the input prompt.
2. Structured Output Generation: Design a prompt structure that builds upon previous sections:
a) Introduction
b) Key Points (referencing the introduction)
c) Detailed Analysis (expanding on key points and referencing previous sections)
d) Conclusion (summarizing and synthesizing all previous content)
e) Final Review and Refinement
3. Few-Shot Prompting: Provide 2-3 relevant examples demonstrating the desired output format, reasoning, and effective use of previous context.
4. Chain-of-Thought (CoT) and Zero-Shot CoT: Incorporate step-by-step reasoning in your instructions, explaining the thought process for each enhancement and how to handle unfamiliar tasks.
5. Self-Consistency: Generate multiple reasoning paths and select the most consistent one for the final improved prompt.
6. Least-to-Most Prompting: Break down complex aspects of the prompt into smaller, manageable sub-tasks that build upon each other.
7. Tree-of-Thought: Create a branching structure for exploring multiple improvement paths simultaneously, considering different aspects of the prompt.
8. Prompt Paraphrasing: Rephrase key instructions in multiple ways to ensure clarity and comprehension.
9. Self-Calibration: Include steps for the AI to assess its own confidence in the generated output and adjustments.
10. Self-Refine: Implement an iterative process for the AI to improve its initial response to the prompt enhancement task.
11. Self-Verification and Chain-of-Verification (COVE): Add verification steps to check the logical consistency, effectiveness, and fulfillment of all requirements in the improved prompt.
12. Cumulative Reasoning: Build upon previous enhancements, accumulating improvements throughout the process.
13. Style Prompting: Adjust the language style of the prompt to match the intended audience or purpose.
14. Emotion Prompting: Incorporate language that emphasizes the importance and impact of the task described in the prompt.
15. System 2 Attention (S2A): Guide the AI to focus on specific critical aspects of the prompt that require careful consideration.
16. Rephrase and Respond (RaR): After each major enhancement, instruct the AI to rephrase the prompt and respond to it to test its effectiveness.
17. Re-reading (RE2): Instruct the AI to re-read the original and enhanced prompts multiple times to catch nuances and potential improvements.
18. Self-Ask: Encourage the AI to ask itself questions about the prompt's clarity, effectiveness, and potential weaknesses, especially in relation to using previous context.
19. Automatic Chain-of-Thought (Auto-CoT): Generate intermediate reasoning steps automatically to support the prompt enhancement process.
20. Program-of-Thoughts: Structure the prompt improvement process as a series of logical operations or a program-like sequence.
21. Skeleton-of-Thought: Create a basic structure or skeleton for the enhanced prompt, then iteratively fill in the details.
22. Mixture of Reasoning Experts (MoRE): Combine insights from multiple expert perspectives (e.g., subject matter expert, language specialist, task optimization expert) to enhance the prompt.
23. Max Mutual Information Method: Optimize the prompt to maximize the mutual information between the input and desired output.
Now, apply these techniques to improve the following prompt:
Initial Prompt: [Insert initial prompt here]
Follow these steps to generate an enhanced version of the prompt:
1. Analyze the original prompt, identifying its main objectives, strengths, and weaknesses.
2. Apply the role of an Expert Prompt Analyst and Optimizer, considering the subject matter.
3. Design a structured output format that encourages use of previous context.
4. Use the Tree-of-Thought technique to explore multiple enhancement paths.
5. For each path, apply Chain-of-Thought reasoning to explain the enhancements.
6. Incorporate Few-Shot examples to illustrate the desired outcome and effective use of previous context.
7. Break down complex aspects using Least-to-Most Prompting.
8. Rephrase key instructions using Prompt Paraphrasing.
9. Adjust the language style and incorporate emotional elements as appropriate.
10. Implement Self-Verification and Chain-of-Verification steps.
11. Use Self-Ask to critically evaluate the enhancements, especially regarding context usage.
12. Apply the Skeleton-of-Thought technique to structure the improved prompt.
13. Utilize the Mixture of Reasoning Experts approach to refine the prompt from multiple perspectives.
14. Employ the Max Mutual Information Method to optimize the prompt's effectiveness.
15. Use Self-Calibration to assess the confidence in the final enhanced prompt.
16. Apply Self-Refine to iteratively improve the enhanced prompt.
Present the final enhanced prompt, along with a brief explanation of the key improvements and techniques used. Ensure that the enhanced prompt:
1. Maintains the original intent
2. Significantly improves effectiveness and clarity
3. Effectively leverages previously generated context
4. Includes explicit instructions for the AI to refer back to and build upon its own previous outputs
5. Creates a cohesive and interconnected result
Your enhanced prompt should guide the AI to generate a response that not only addresses the original query but also demonstrates a clear progression of thought and utilization of previously generated information throughout the response.
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string as bullet points format",
"refined_prompt": "Your refined prompt",
"explanation_of_refinements": "Explain techniques used and improvements made, including the extract of final prompt where it used. Answer in a string "
}
</json>
"""
loic_metaprompt = """
Given an initial prompt:
Initial Prompt: [Insert initial prompt here]
Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Leverage Autoregressive Nature: Strategically order information to prime the model for better results. Generate key concepts, context, or vocabulary early in the prompt to inform later reasoning and outputs.
- Reasoning Before Conclusions: Encourage reasoning steps before any conclusions are reached. If user examples show reasoning afterward, reverse the order. Never start examples with conclusions.
- Reasoning Order: Identify reasoning and conclusion parts. Determine their order and reverse if needed. Conclusions, classifications, or results should always appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- Assess example needs, quantity, and complexity for potential placeholder use.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. Avoid code blocks unless requested.
- Preserve User Content: Retain extensive guidelines or examples from input. Break down vague instructions into sub-steps. Maintain user-provided details, guidelines, examples, variables, or placeholders.
- Constants: Include constants (guides, rubrics, examples) as they resist prompt injection.
- Output Format: Specify appropriate output format in detail, including length and syntax.
- For structured data, prefer JSON output (unwrapped unless requested).
The final prompt should follow this structure, with no additional commentary:
Leverage Autoregressive Nature: Strategically order information to prime the model for better results. Generate key concepts, context, or vocabulary early in the prompt to inform later reasoning and outputs.
[Concise task instruction - first line, no header]
[Additional details as needed]
[Optional sections with headings or bullet points for detailed steps]
# Context Generation
[Instructions for generating key concepts, vocabulary, or context to inform later reasoning]
# Steps [optional]
[Detailed task breakdown]
# Reasoning Process
[Specific instructions for the reasoning process, ensuring it precedes conclusions]
# Output Format
[Detailed output format specifications]
# Examples [optional]
[1-3 well-defined examples with placeholders if necessary. Mark input/output clearly. Use placeholders and indicate if real examples differ in length/complexity]
# Notes [optional]
[Edge cases, important considerations, repeated key points]
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string",
"refined_prompt": "Your refined prompt into quote",
"explanation_of_refinements": "Explanation of the techniques used and improvements made, also include the extract of final prompt where it made.Answer in bullet points if accurate"
}
</json>
"""
openai_metaprompt='''
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
# Guidelines
- Understand the Task: Grasp the main objective, goals, requirements, constraints, and expected output.
- Minimal Changes: If an existing prompt is provided, improve it only if it's simple. For complex prompts, enhance clarity and add missing elements without altering the original structure.
- Reasoning Before Conclusions**: Encourage reasoning steps before any conclusions are reached. ATTENTION! If the user provides examples where the reasoning happens afterward, REVERSE the order! NEVER START EXAMPLES WITH CONCLUSIONS!
- Reasoning Order: Call out reasoning portions of the prompt and conclusion parts (specific fields by name). For each, determine the ORDER in which this is done, and whether it needs to be reversed.
- Conclusion, classifications, or results should ALWAYS appear last.
- Examples: Include high-quality examples if helpful, using placeholders [in brackets] for complex elements.
- What kinds of examples may need to be included, how many, and whether they are complex enough to benefit from placeholders.
- Clarity and Conciseness: Use clear, specific language. Avoid unnecessary instructions or bland statements.
- Formatting: Use markdown features for readability. DO NOT USE ``` CODE BLOCKS UNLESS SPECIFICALLY REQUESTED.
- Preserve User Content: If the input task or prompt includes extensive guidelines or examples, preserve them entirely, or as closely as possible. If they are vague, consider breaking down into sub-steps. Keep any details, guidelines, examples, variables, or placeholders provided by the user.
- Constants: DO include constants in the prompt, as they are not susceptible to prompt injection. Such as guides, rubrics, and examples.
- Output Format: Explicitly the most appropriate output format, in detail. This should include length and syntax (e.g. short sentence, paragraph, JSON, etc.)
- For tasks outputting well-defined or structured data (classification, JSON, etc.) bias toward outputting a JSON.
- JSON should never be wrapped in code blocks (```) unless explicitly requested.
The final prompt you output should adhere to the following structure below. Do not include any additional commentary, only output the completed system prompt. SPECIFICALLY, do not include any additional messages at the start or end of the prompt. (e.g. no "---")
[Concise instruction describing the task - this should be the first line in the prompt, no section header]
[Additional details as needed.]
[Optional sections with headings or bullet points for detailed steps.]
# Steps [optional]
[optional: a detailed breakdown of the steps necessary to accomplish the task]
# Output Format
[Specifically call out how the output should be formatted, be it response length, structure e.g. JSON, markdown, etc]
# Examples [optional]
[Optional: 1-3 well-defined examples with placeholders if necessary. Clearly mark where examples start and end, and what the input and output are. User placeholders as necessary.]
[If the examples are shorter than what a realistic example is expected to be, make a reference with () explaining how real examples should be longer / shorter / different. AND USE PLACEHOLDERS! ]
# Notes [optional]
[optional: edge cases, details, and an area to call or repeat out specific important considerations]
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string on markdown bullet points format",
"refined_prompt": "Your refined prompt",
"explanation_of_refinements": "Explanation of the techniques used and improvements made, also include the extract of final prompt where it made. Answer in bullet points if accurate"
}
</json>
'''
original_meta_prompt = '''Create an effective prompt from this one:
Initial Prompt: [Insert initial prompt here]
Use these simple steps:
1. Look at the task closely, focusing on goals, needs, and limits.
2. Make prompts better by making language clear without changing the main idea.
3. Keep a logical flow by putting reasoning steps first.
4. Use good examples with [placeholders] for tricky parts.
5. Use simple words; remove unneeded instructions.
6. Use markdown for easy reading; skip code blocks unless needed.
7. Keep user content like guides and examples.
8. Add constants like guides and rubrics.
9. Clearly state output format including structure and syntax.
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string as bullet points format",
"refined_prompt": "Your refined prompt",
"explanation_of_refinements": "Explanation of the techniques used and improvements made, also include the extract of final prompt where it made. Answer in bullet points if accurate"
}
</json>
'''
new_meta_prompt = '''Given an initial prompt:
Initial Prompt: [Insert initial prompt here]
follow these steps to refine the prompt:
1. Analyze the prompt:
- Identify the main topic and key concepts
- Determine the type of task (e.g., math problem, logical reasoning, factual question)
- Assess the complexity and any specific requirements
2. Evaluate the initial prompt:
- Determine its strengths and weaknesses in relation to the query
- Identify any missing elements or irrelevant information
3. Refine the prompt:
- Retain relevant parts of the initial prompt
- Add query-specific context or information
- Incorporate appropriate reasoning frameworks (e.g., step-by-step, chain-of-thought)
- Ensure clear instructions for the desired output format
4. Optimize for information flow:
- Ensure the refined prompt allows for direct use of query information
- Enable indirect information aggregation through prompt-guided reasoning
5. Enhance versatility:
- Add elements that encourage flexible thinking and problem-solving
- Include self-evaluation or error-checking instructions if appropriate
6. Formulate the refined prompt:
- Combine all elements into a clear, concise, and effective prompt
- Ensure the language and structure are appropriate for the task
7. Output the refined prompt:
- Present the new prompt, highlighting key changes or additions
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string as bullet points format",
"refined_prompt": "Your refined prompt",
"explanation_of_refinements": "Explanation of the techniques used and improvements made, also include the extract of final prompt where it made. Answer in bullet points if accurate"
}
</json>
'''
advanced_meta_prompt = '''
You are an expert in natural language processing and state-of-the-art prompt engineering. Your task is to refine and improve the given prompt using advanced prompt engineering techniques.
Initial Prompt: [Insert initial prompt here]
Analyze the initial prompt and generate an improved version. Apply various prompt engineering techniques to enhance clarity, specificity, and effectiveness. Consider techniques such as:
1. Clarity and Specificity
2. Structural Improvement
3. Conciseness
4. Ambiguity Resolution
5. Instruction Refinement
6. Query Focusing
7. Task Decomposition
8. Role-Playing
9. Chain-of-Thought
10. Few-Shot Learning
11. Constrained Generation
12. Metacognitive Prompting
13. Contextual Priming
14. Negative Prompting
15. Output Format Control
16. Emotional Tone Setting
17. Iterative Refinement
18. Analogical Reasoning
19. Perspective Shifting
Only provide the output in the following JSON format enclosed in <json> tags:
<json>
{
"initial_prompt_evaluation": "Your evaluation of the initial prompt with Strengths and Weaknesses in a string as bullet points format",
"refined_prompt": "Your refined prompt",
"explanation_of_refinements": "Explanation of the techniques used and improvements made, also include the extract of final prompt where it made. Answer in bullet points if accurate"
}
</json>
'''
import json
import re
import json
import re
from huggingface_hub import InferenceClient
from pydantic import BaseModel, Field
from typing import Optional, Literal
class PromptInput(BaseModel):
text: str = Field(..., description="The initial prompt text")
meta_prompt_choice: Literal["star","done","physics","morphosis", "verse", "phor","bolism"] = Field(..., description="Choice of meta prompt strategy")
class RefinementOutput(BaseModel):
query_analysis: Optional[str] = None
initial_prompt_evaluation: Optional[str] = None
refined_prompt: Optional[str] = None
explanation_of_refinements: Optional[str] = None
raw_content: Optional[str] = None
class PromptRefiner:
def __init__(self, api_token: str):
self.client = InferenceClient(token=api_token)
def refine_prompt(self, prompt_input: PromptInput) -> RefinementOutput:
if prompt_input.meta_prompt_choice == "morphosis":
selected_meta_prompt = original_meta_prompt
elif prompt_input.meta_prompt_choice == "verse":
selected_meta_prompt = new_meta_prompt
elif prompt_input.meta_prompt_choice == "physics":
selected_meta_prompt = metaprompt1
elif prompt_input.meta_prompt_choice == "bolism":
selected_meta_prompt = loic_metaprompt
elif prompt_input.meta_prompt_choice == "done":
selected_meta_prompt = metadone
elif prompt_input.meta_prompt_choice == "star":
selected_meta_prompt = echo_prompt_refiner
else:
selected_meta_prompt = 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)}
]
response = self.client.chat_completion(
model="meta-llama/Meta-Llama-3-70B-Instruct",
messages=messages,
max_tokens=4000,
temperature=0.3
)
response_content = response.choices[0].message.content.strip()
try:
# Extract JSON from between <json> tags
json_match = re.search(r'<json>\s*(.*?)\s*</json>', response_content, re.DOTALL)
if json_match:
json_str = json_match.group(1)
# Remove newlines and escape quotes within the JSON string
json_str = re.sub(r'\n\s*', ' ', json_str)
json_str = json_str.replace('"', '\\"')
# Wrap the entire string in quotes and parse it
json_output = json.loads(f'"{json_str}"')
# Ensure json_output is a dictionary
if isinstance(json_output, str):
json_output = json.loads(json_output)
# Unescape the parsed JSON
for key, value in json_output.items():
if isinstance(value, str):
json_output[key] = value.replace('\\"', '"')
return RefinementOutput(**json_output, raw_content=response_content)
else:
raise ValueError("No JSON found in the response")
except (json.JSONDecodeError, ValueError) as e:
print(f"Error parsing JSON: {e}")
print(f"Raw content: {response_content}")
# If JSON parsing fails, attempt to extract the content manually
output = {}
for key in ["initial_prompt_evaluation", "refined_prompt", "explanation_of_refinements"]:
pattern = rf'"{key}":\s*"(.*?)"(?:,|\}})'
match = re.search(pattern, response_content, re.DOTALL)
if match:
output[key] = match.group(1).replace('\\n', '\n').replace('\\"', '"')
else:
output[key] = "" # Set empty string if content not found
return RefinementOutput(**output, raw_content=response_content)
def apply_prompt(self, prompt: 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}
]
response = self.client.chat_completion(
model="meta-llama/Meta-Llama-3-70B-Instruct",
messages=messages,
max_tokens=4000, # Increased token limit
temperature=0.8
)
output = response.choices[0].message.content.strip()
# Basic post-processing
output = output.replace('\n\n', '\n').strip()
return output
except Exception as e:
return f"Error: {str(e)}"
class GradioInterface:
def __init__(self, prompt_refiner: PromptRefiner):
self.prompt_refiner = prompt_refiner
with gr.Blocks() as self.interface:
gr.Markdown("# PROMPT++")
gr.Markdown("### Automating Prompt Engineering by Refining your Prompts")
gr.Markdown("#### Learn how to generate an improved version of your prompts")
gr.Markdown("Enter a main idea for a prompt, choose a meta prompt, and the model will attempt to generate an improved version.")
with gr.Row():
prompt_text = gr.Textbox(label="Type the prompt here")
with gr.Row():
meta_prompt_choice = gr.Radio(["star","done","physics","morphosis", "verse", "phor","bolism"], label="Choose Meta Prompt", value="morphosis")
refine_button = gr.Button("Refine Prompt")
with gr.Row():
gr.Markdown("### Initial prompt analysis")
with gr.Column():
analysis_evaluation = gr.Markdown(label="Analysis and Evaluation")
gr.Markdown("### Refined Prompt")
refined_prompt = gr.Textbox(label="Refined Prompt")
gr.Markdown("### Explanation of Refinements")
explanation_of_refinements = gr.Markdown(label="Explanation of Refinements")
with gr.Accordion("Full Response JSON", open=False):
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]
)
with gr.Row():
# apply_model=gr.Dropdown(["meta-llama/Llama-3.1-70B-Instruct",'Qwen/Qwen2.5-72B-Instruct'], value="meta-llama/Llama-3.1-70B-Instruct", label="Model"),
apply_button = gr.Button("Apply Prompts")
with gr.Row():
with gr.Column():
gr.Markdown("### Original Prompt Output")
original_output = gr.Markdown(label="Original Prompt Output")
with gr.Column():
gr.Markdown("### Refined Prompt Output")
refined_output = gr.Markdown(label="Refined Prompt Output")
apply_button.click(
fn=self.apply_prompts,
inputs=[prompt_text, refined_prompt],
outputs=[original_output, refined_output]
)
gr.Examples(
examples=[
["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"],
["Write a story.", "bolism"],
["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 ?", "star"],
],
inputs=[prompt_text, meta_prompt_choice]
)
def refine_prompt(self, prompt: str, meta_prompt_choice: str) -> tuple:
input_data = PromptInput(text=prompt, meta_prompt_choice=meta_prompt_choice)
result = self.prompt_refiner.refine_prompt(input_data)
analysis_evaluation = f"\n\n{result.initial_prompt_evaluation}"
return (
analysis_evaluation,
result.refined_prompt,
result.explanation_of_refinements,
result.dict()
)
def apply_prompts(self,original_prompt: str, refined_prompt: str):
original_output = self.prompt_refiner.apply_prompt(original_prompt)
refined_output = self.prompt_refiner.apply_prompt(refined_prompt)
return original_output, refined_output
def launch(self):
self.interface.launch()
# Main code to run the application
if __name__ == '__main__':
api_token = os.getenv('HF_API_TOKEN')
if not api_token:
raise ValueError("HF_API_TOKEN not found in environment variables")
prompt_refiner = PromptRefiner(api_token)
gradio_interface = GradioInterface(prompt_refiner)
gradio_interface.launch() |