Spaces:
Sleeping
Sleeping
Download app.py from itsahab01/AI-Prompt-Assistant: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/spaces/itsahab01/AI-Prompt-Assistant/resolve/main/app.py
- Command line
-
hf download hf://spaces/itsahab01/AI-Prompt-Assistant/app.py
-
curl -L -o app.py https://huggingface.co/spaces/itsahab01/AI-Prompt-Assistant/resolve/main/app.py
12.5 kB
| """ | |
| AI Prompt Assistant β Prompt Engineering Evaluator & Optimizer | |
| Track C Capstone | |
| """ | |
| import torch | |
| import gradio as gr | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| # ββ Model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.float16 if device == "cuda" else torch.float32 | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_ID, | |
| dtype=dtype, | |
| device_map="auto", | |
| ) | |
| # ββ System Prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| SYSTEM_PROMPT = """You are an expert Prompt Engineering evaluator and optimizer. | |
| Your goal is to evaluate prompts, identify weaknesses, and rewrite them using | |
| prompt engineering best practices while preserving the user's original intent. | |
| ## THE FIVE ESSENTIAL PROMPT COMPONENTS | |
| 1. Instructions β clear, specific, action-oriented, unambiguous description of the task. | |
| 2. Role β an appropriate persona assigned to the AI before the task. | |
| 3. Context β background info: goals, audience, constraints, environment, project details. | |
| 4. Input Data β the actual content the model should work with. Flag if missing. | |
| 5. Output Format β exact structure required (list, table, JSON, Markdown, report, etc.). | |
| ## CHARACTERISTICS OF A HIGH-QUALITY PROMPT | |
| Clear, specific, goal-oriented, rich in context, appropriate for the audience, | |
| explicit about the desired output, easy to understand, free from conflicting instructions. | |
| ## COMMON PROMPT MISTAKES | |
| Vague instructions, missing context, undefined objective, missing output format, | |
| conflicting instructions, missing input information, expecting perfect results | |
| from the first attempt. | |
| ## BEST PRACTICES | |
| Be clear. Be specific. Define the role. Provide context. Include necessary input. | |
| Specify the output format. Use positive instructions. Include examples when helpful. | |
| Iterate and refine prompts. | |
| ## EVALUATION FRAMEWORK (follow in this exact order β do not skip steps) | |
| 1. Identify the objective of the prompt. | |
| 2. Go through the five essential components ONE BY ONE and mark each as | |
| Present, Weak, or Missing. | |
| 3. List every component marked Weak or Missing as a bullet point under | |
| Weaknesses, explaining briefly why it hurts the prompt's quality. | |
| 4. List genuine strengths ONLY for components that are clearly Present | |
| and well-defined. | |
| 5. Assign an Overall Score using the Scoring Guide below, consistent with | |
| steps 2-4 β the score must reflect how many components are Present. | |
| 6. Suggest concrete, actionable improvements. | |
| 7. Rewrite the prompt while preserving the original intent. | |
| ## SCORING GUIDE (anchor β do not deviate without explicit justification) | |
| - All 5 components Present, clear and specific β 8-10 | |
| - 3-4 components Present β 5-7 | |
| - 1-2 components Present β 2-4 | |
| - 0 components Present, or input is empty/nonsensical β 0-1 | |
| Any score outside this range for the number of Present components must be | |
| explicitly justified as a bullet point in Weaknesses. | |
| ## CONSISTENCY RULE (mandatory β violating this is a critical error) | |
| - Every component marked Weak or Missing in the Five Components Review | |
| MUST also appear as a bullet point in Weaknesses. | |
| - NEVER write "no weaknesses" or "none identified" if any component is | |
| marked Weak or Missing. | |
| - The Overall Score MUST match the Scoring Guide based on the number of | |
| Present components β do not contradict your own component review. | |
| ## EVALUATION CRITERIA | |
| Clarity, Specificity, Completeness, Context Quality, Role Definition, Input Quality, | |
| Output Definition, Constraints, Practicality, Expected Accuracy. | |
| ## RESPONSE RULES | |
| - Always respond in well-structured Markdown using the exact section headers below, | |
| in the exact order shown. | |
| - Never hallucinate requirements. Never change the user's original task. | |
| - If the user's prompt is written in Arabic, respond in Arabic. Otherwise respond in English. | |
| - If input is empty, nonsensical, or not a prompt at all, say so clearly instead of | |
| inventing an evaluation. | |
| - Always state the Overall Score in the exact format "X/10" (e.g., "3/10"), never a bare number alone. | |
| ## REQUIRED OUTPUT STRUCTURE (this order is mandatory) | |
| ### Overall Score | |
| ### Weaknesses | |
| ### Strengths | |
| ### Improvement Suggestions | |
| ### Optimized Prompt | |
| ### Clarifying Questions | |
| (omit this last section only if none are needed) | |
| """ | |
| # ββ Prompt Template βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def build_messages(user_prompt: str) -> list: | |
| user_turn = f"""Evaluate the following prompt according to your methodology. | |
| PROMPT TO EVALUATE: | |
| \"\"\" | |
| {user_prompt.strip()} | |
| \"\"\" | |
| Follow the Evaluation Framework step by step and return the Required Output Structure.""" | |
| return [ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": user_turn}, | |
| ] | |
| # ββ Evaluate Function ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Core generation logic β isolated from the UI so it can be reused (Gradio, tests, HF Space) | |
| import re | |
| def check_output_consistency(result: str) -> str: | |
| """ | |
| Safety net: flags cases where a component was marked Missing/Weak in | |
| 'Five Components Review' but not reflected in 'Weaknesses'. | |
| Does NOT rewrite the model's output β only appends a visible note if | |
| an inconsistency is detected, so it never fails silently. | |
| """ | |
| fc_match = re.search(r"###\s*Five Components Review(.*?)(###|\Z)", result, re.S | re.I) | |
| weak_match = re.search(r"###\s*Weaknesses(.*?)(###|\Z)", result, re.S | re.I) | |
| if not fc_match or not weak_match: | |
| return result # sections not found (e.g. empty-input message) β skip silently | |
| fc_text = fc_match.group(1) | |
| weak_text = weak_match.group(1).lower() | |
| flagged = [] | |
| for line in fc_text.splitlines(): | |
| m = re.match(r"\s*\d+\.\s*\*\*(.+?)\*\*[:οΌ]\s*(Missing|Weak)", line, re.I) | |
| if m: | |
| component = m.group(1).strip() | |
| if component.lower() not in weak_text: | |
| flagged.append(component) | |
| if flagged: | |
| note = ( | |
| "\n\n---\nβ οΈ **Consistency check:** the following component(s) were " | |
| f"marked Missing/Weak but weren't reflected in Weaknesses: {', '.join(flagged)}. " | |
| "Please double-check the Five Components Review section above." | |
| ) | |
| result += note | |
| return result | |
| def evaluate_prompt(user_prompt: str, temperature: float = 0.15, | |
| top_p: float = 0.9, max_new_tokens: int = 1600, | |
| repetition_penalty: float = 1.1) -> str: | |
| # Trustworthy-AI: handle empty/bad input gracefully instead of calling the model | |
| if not user_prompt or not user_prompt.strip(): | |
| return "β οΈ **No prompt provided.** Please paste a prompt to evaluate." | |
| if len(user_prompt.strip()) < 5: | |
| return "β οΈ **Input too short.** Please provide a full prompt to evaluate." | |
| messages = build_messages(user_prompt) | |
| text = tokenizer.apply_chat_template( | |
| messages, tokenize=False, add_generation_prompt=True | |
| ) | |
| inputs = tokenizer(text, return_tensors="pt").to(model.device) | |
| with torch.no_grad(): | |
| output_ids = model.generate( | |
| **inputs, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=temperature > 0, | |
| temperature=max(temperature, 0.01), | |
| top_p=top_p, | |
| repetition_penalty=repetition_penalty, | |
| pad_token_id=tokenizer.eos_token_id, | |
| ) | |
| # Only decode the newly generated tokens, not the input prompt | |
| new_tokens = output_ids[0][inputs["input_ids"].shape[-1]:] | |
| result = tokenizer.decode(new_tokens, skip_special_tokens=True).strip() | |
| return check_output_consistency(result) | |
| # ββ Fixed generation settings (not user-adjustable) ββββββββββββββββββββββ | |
| TEMPERATURE = 0.15 | |
| MAX_NEW_TOKENS = 1600 | |
| REPETITION_PENALTY = 1.1 | |
| def run_evaluation(prompt_text): | |
| return evaluate_prompt( | |
| prompt_text, | |
| temperature=TEMPERATURE, | |
| max_new_tokens=MAX_NEW_TOKENS, | |
| repetition_penalty=REPETITION_PENALTY, | |
| ) | |
| # ββ Styling β dark mode, blue accent (forced, not browser-dependent) ββββ | |
| CUSTOM_CSS = """ | |
| @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&display=swap'); | |
| :root, .dark { | |
| color-scheme: dark; | |
| --body-background-fill: #0B0F19 !important; | |
| --background-fill-primary: #0B0F19 !important; | |
| --background-fill-secondary: #151A26 !important; | |
| --block-background-fill: #151A26 !important; | |
| --block-border-color: #262C3A !important; | |
| --border-color-primary: #262C3A !important; | |
| --input-background-fill: #101521 !important; | |
| --body-text-color: #E7EAF0 !important; | |
| --body-text-color-subdued: #8D97AB !important; | |
| --block-title-text-color: #E7EAF0 !important; | |
| --button-primary-background-fill: #3B82F6 !important; | |
| --button-primary-background-fill-hover: #2563EB !important; | |
| --button-primary-text-color: #FFFFFF !important; | |
| --button-secondary-background-fill: #1C2230 !important; | |
| --button-secondary-text-color: #E7EAF0 !important; | |
| } | |
| body, .gradio-container { | |
| background: #0B0F19 !important; | |
| font-family: 'Inter', sans-serif !important; | |
| } | |
| #app-header h1 { | |
| font-family: 'Space Grotesk', sans-serif !important; | |
| font-weight: 700 !important; | |
| color: #E7EAF0 !important; | |
| font-size: 2rem !important; | |
| margin-bottom: 0.25rem !important; | |
| } | |
| #app-header p { color: #8D97AB !important; } | |
| .prompt-box textarea { | |
| background: #101521 !important; | |
| color: #E7EAF0 !important; | |
| border: 1px solid #262C3A !important; | |
| border-radius: 12px !important; | |
| } | |
| #evaluate-btn { | |
| background: #3B82F6 !important; | |
| border: none !important; | |
| color: #fff !important; | |
| font-weight: 600 !important; | |
| border-radius: 10px !important; | |
| } | |
| #evaluate-btn:hover { background: #2563EB !important; } | |
| .result-card { | |
| background: #151A26 !important; | |
| border: 1px solid #262C3A !important; | |
| border-radius: 14px !important; | |
| padding: 24px !important; | |
| color: #E7EAF0 !important; | |
| } | |
| .result-card h3 { | |
| font-family: 'Space Grotesk', sans-serif !important; | |
| color: #60A5FA !important; | |
| border-bottom: 1px solid #262C3A !important; | |
| padding-bottom: 6px !important; | |
| } | |
| """ | |
| THEME = gr.themes.Base( | |
| primary_hue=gr.themes.colors.blue, | |
| neutral_hue=gr.themes.colors.slate, | |
| font=[gr.themes.GoogleFont("Inter"), "sans-serif"], | |
| ) | |
| EXAMPLES = [ | |
| ["write me something about Programming"], | |
| ["Summarize this article for me."], | |
| ["You are a senior Python developer. Review the following code for bugs and suggest fixes:\n\n[paste code here]\n\nReturn your review as a bullet list."], | |
| ] | |
| with gr.Blocks(title="AI Prompt Assistant", theme=THEME, css=CUSTOM_CSS) as demo: | |
| with gr.Column(elem_id="app-header"): | |
| gr.Markdown("# AI Prompt Assistant") | |
| gr.Markdown("Paste any prompt and get an expert evaluation β score, strengths, weaknesses, and an optimized rewrite.") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| prompt_input = gr.Textbox( | |
| label="Your Prompt", placeholder="Paste the prompt you want evaluated...", | |
| lines=10, elem_classes=["prompt-box"], | |
| ) | |
| with gr.Row(): | |
| clear_btn = gr.ClearButton(value="Clear") | |
| submit_btn = gr.Button("Evaluate Prompt", elem_id="evaluate-btn") | |
| gr.Examples(examples=EXAMPLES, inputs=[prompt_input], label="Try an example") | |
| with gr.Column(scale=1): | |
| output_md = gr.Markdown(elem_classes=["result-card"]) | |
| submit_btn.click(fn=run_evaluation, | |
| inputs=[prompt_input], | |
| outputs=[output_md]) | |
| clear_btn.add([prompt_input, output_md]) | |
| if __name__ == "__main__": | |
| demo.launch() | |