Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -5,19 +5,6 @@ from groq import Groq
|
|
| 5 |
# =============================================================================
|
| 6 |
# Prompt Optimizer
|
| 7 |
# =============================================================================
|
| 8 |
-
# Transforms basic prompts into well-structured instructions using LLM analysis.
|
| 9 |
-
#
|
| 10 |
-
# Optimization Techniques:
|
| 11 |
-
# 1. Clarity & Specificity
|
| 12 |
-
# 2. Role/Persona Framing
|
| 13 |
-
# 3. Output Format Instructions
|
| 14 |
-
# 4. Constraints & Guardrails
|
| 15 |
-
# 5. Task Decomposition
|
| 16 |
-
#
|
| 17 |
-
# References:
|
| 18 |
-
# - OpenAI Prompt Engineering Guide
|
| 19 |
-
# - Anthropic Claude Documentation
|
| 20 |
-
# =============================================================================
|
| 21 |
|
| 22 |
# Initialize Groq client
|
| 23 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
|
@@ -95,16 +82,12 @@ def optimize_prompt(user_prompt: str, context: str = "") -> dict:
|
|
| 95 |
"changes": "",
|
| 96 |
"raw_response": ""
|
| 97 |
}
|
| 98 |
-
|
| 99 |
-
user_message =
|
| 100 |
-
|
| 101 |
-
{user_prompt}"
|
| 102 |
-
|
| 103 |
if context.strip():
|
| 104 |
-
user_message +=
|
| 105 |
-
|
| 106 |
-
Additional context: {context}"
|
| 107 |
-
|
| 108 |
response = client.chat.completions.create(
|
| 109 |
model=MODEL,
|
| 110 |
messages=[
|
|
@@ -114,36 +97,36 @@ Additional context: {context}"
|
|
| 114 |
max_tokens=2000,
|
| 115 |
temperature=0.7
|
| 116 |
)
|
| 117 |
-
|
| 118 |
raw_response = response.choices[0].message.content
|
| 119 |
-
|
| 120 |
result = {
|
| 121 |
"analysis": "",
|
| 122 |
"optimized_prompt": "",
|
| 123 |
"changes": "",
|
| 124 |
"raw_response": raw_response
|
| 125 |
}
|
| 126 |
-
|
| 127 |
if "**ANALYSIS:**" in raw_response:
|
| 128 |
parts = raw_response.split("**ANALYSIS:**")
|
| 129 |
if len(parts) > 1:
|
| 130 |
remainder = parts[1]
|
| 131 |
-
|
| 132 |
if "**OPTIMIZED PROMPT:**" in remainder:
|
| 133 |
analysis_part, remainder = remainder.split("**OPTIMIZED PROMPT:**", 1)
|
| 134 |
result["analysis"] = analysis_part.strip()
|
| 135 |
-
|
| 136 |
if "**CHANGES MADE:**" in remainder:
|
| 137 |
prompt_part, changes_part = remainder.split("**CHANGES MADE:**", 1)
|
| 138 |
result["optimized_prompt"] = prompt_part.strip()
|
| 139 |
result["changes"] = changes_part.strip()
|
| 140 |
else:
|
| 141 |
result["optimized_prompt"] = remainder.strip()
|
| 142 |
-
|
| 143 |
if not result["optimized_prompt"]:
|
| 144 |
result["optimized_prompt"] = raw_response
|
| 145 |
result["analysis"] = "Could not parse structured response."
|
| 146 |
-
|
| 147 |
return result
|
| 148 |
|
| 149 |
|
|
@@ -155,20 +138,16 @@ def process_optimization(prompt: str, context: str) -> tuple:
|
|
| 155 |
"",
|
| 156 |
""
|
| 157 |
)
|
| 158 |
-
|
| 159 |
try:
|
| 160 |
result = optimize_prompt(prompt, context)
|
| 161 |
-
|
| 162 |
-
analysis =
|
| 163 |
-
|
| 164 |
-
{result['analysis']}"
|
| 165 |
optimized = result['optimized_prompt']
|
| 166 |
-
changes =
|
| 167 |
-
|
| 168 |
-
{result['changes']}"
|
| 169 |
-
|
| 170 |
return analysis, optimized, changes
|
| 171 |
-
|
| 172 |
except Exception as e:
|
| 173 |
return (
|
| 174 |
f"❌ Error: {str(e)}",
|
|
@@ -195,11 +174,11 @@ demo = gr.Blocks()
|
|
| 195 |
with demo:
|
| 196 |
gr.Markdown("""
|
| 197 |
# ✨ Prompt Optimizer
|
| 198 |
-
|
| 199 |
Transform basic prompts into powerful, well-structured instructions that get better results from AI.
|
| 200 |
-
|
| 201 |
**How it works:** Enter your rough prompt → AI analyzes weaknesses → Returns an optimized version with explanations.
|
| 202 |
-
|
| 203 |
**Optimization Techniques Applied:**
|
| 204 |
- 🎯 Clarity & Specificity
|
| 205 |
- 🎭 Role/Persona Framing
|
|
@@ -207,87 +186,83 @@ with demo:
|
|
| 207 |
- 🚧 Constraints & Guardrails
|
| 208 |
- 🔢 Task Decomposition
|
| 209 |
""")
|
| 210 |
-
|
| 211 |
with gr.Row():
|
| 212 |
with gr.Column(scale=1):
|
| 213 |
gr.Markdown("### 📝 Input")
|
| 214 |
-
|
| 215 |
prompt_input = gr.Textbox(
|
| 216 |
label="Your Prompt",
|
| 217 |
-
placeholder="Enter the prompt you want to optimize...
|
| 218 |
-
|
| 219 |
-
Example: 'write about dogs'",
|
| 220 |
lines=4
|
| 221 |
)
|
| 222 |
-
|
| 223 |
context_input = gr.Textbox(
|
| 224 |
label="Additional Context (Optional)",
|
| 225 |
-
placeholder="Any extra context about how you'll use this prompt...
|
| 226 |
-
|
| 227 |
-
Example: 'For a children's educational website'",
|
| 228 |
lines=2
|
| 229 |
)
|
| 230 |
-
|
| 231 |
optimize_btn = gr.Button("✨ Optimize Prompt", variant="primary")
|
| 232 |
-
|
| 233 |
gr.Markdown("### 💡 Example Prompts")
|
| 234 |
gr.Examples(
|
| 235 |
examples=EXAMPLES,
|
| 236 |
inputs=[prompt_input, context_input],
|
| 237 |
label=""
|
| 238 |
)
|
| 239 |
-
|
| 240 |
with gr.Column(scale=1):
|
| 241 |
gr.Markdown("### 🎯 Results")
|
| 242 |
-
|
| 243 |
analysis_output = gr.Markdown(label="Analysis")
|
| 244 |
-
|
| 245 |
optimized_output = gr.Textbox(
|
| 246 |
label="Optimized Prompt (Ready to Copy)",
|
| 247 |
lines=10,
|
| 248 |
show_copy_button=True,
|
| 249 |
interactive=False
|
| 250 |
)
|
| 251 |
-
|
| 252 |
changes_output = gr.Markdown(label="Changes Made")
|
| 253 |
-
|
| 254 |
optimize_btn.click(
|
| 255 |
fn=process_optimization,
|
| 256 |
inputs=[prompt_input, context_input],
|
| 257 |
outputs=[analysis_output, optimized_output, changes_output]
|
| 258 |
)
|
| 259 |
-
|
| 260 |
with gr.Accordion("📚 Prompt Engineering Tips", open=False):
|
| 261 |
gr.Markdown("""
|
| 262 |
### Best Practices for Writing Prompts
|
| 263 |
-
|
| 264 |
**1. Be Specific**
|
| 265 |
- ❌ "Write about history"
|
| 266 |
- ✅ "Write a 500-word overview of the causes of World War I, focusing on the alliance system and nationalism"
|
| 267 |
-
|
| 268 |
**2. Define the Output Format**
|
| 269 |
- ❌ "Give me some ideas"
|
| 270 |
- ✅ "Give me 5 ideas as a numbered list, with a one-sentence explanation for each"
|
| 271 |
-
|
| 272 |
**3. Set the Role/Persona**
|
| 273 |
- ❌ "Explain machine learning"
|
| 274 |
- ✅ "You are a computer science professor. Explain machine learning to a first-year undergraduate student"
|
| 275 |
-
|
| 276 |
**4. Add Constraints**
|
| 277 |
- ❌ "Write a story"
|
| 278 |
- ✅ "Write a 300-word short story set in Tokyo, featuring a detective, with a surprise ending. Avoid clichés."
|
| 279 |
-
|
| 280 |
**5. Break Down Complex Tasks**
|
| 281 |
- ❌ "Analyze this data and give recommendations"
|
| 282 |
- ✅ "1) Summarize the key trends in the data. 2) Identify the top 3 issues. 3) Provide actionable recommendations for each issue."
|
| 283 |
-
|
| 284 |
### Resources
|
| 285 |
- [OpenAI Prompt Engineering Guide](https://platform.openai.com/docs/guides/prompt-engineering)
|
| 286 |
- [Anthropic Prompt Engineering](https://docs.anthropic.com/claude/docs/prompt-engineering)
|
| 287 |
""")
|
| 288 |
-
|
| 289 |
with gr.Accordion("🔧 Technical Details", open=False):
|
| 290 |
-
gr.Markdown(
|
| 291 |
| Component | Details |
|
| 292 |
|-----------|---------|
|
| 293 |
| **LLM Backend** | Groq API |
|
|
|
|
| 5 |
# =============================================================================
|
| 6 |
# Prompt Optimizer
|
| 7 |
# =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Initialize Groq client
|
| 10 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
|
|
|
| 82 |
"changes": "",
|
| 83 |
"raw_response": ""
|
| 84 |
}
|
| 85 |
+
|
| 86 |
+
user_message = "Please optimize this prompt:\n\n" + user_prompt
|
| 87 |
+
|
|
|
|
|
|
|
| 88 |
if context.strip():
|
| 89 |
+
user_message += "\n\nAdditional context: " + context
|
| 90 |
+
|
|
|
|
|
|
|
| 91 |
response = client.chat.completions.create(
|
| 92 |
model=MODEL,
|
| 93 |
messages=[
|
|
|
|
| 97 |
max_tokens=2000,
|
| 98 |
temperature=0.7
|
| 99 |
)
|
| 100 |
+
|
| 101 |
raw_response = response.choices[0].message.content
|
| 102 |
+
|
| 103 |
result = {
|
| 104 |
"analysis": "",
|
| 105 |
"optimized_prompt": "",
|
| 106 |
"changes": "",
|
| 107 |
"raw_response": raw_response
|
| 108 |
}
|
| 109 |
+
|
| 110 |
if "**ANALYSIS:**" in raw_response:
|
| 111 |
parts = raw_response.split("**ANALYSIS:**")
|
| 112 |
if len(parts) > 1:
|
| 113 |
remainder = parts[1]
|
| 114 |
+
|
| 115 |
if "**OPTIMIZED PROMPT:**" in remainder:
|
| 116 |
analysis_part, remainder = remainder.split("**OPTIMIZED PROMPT:**", 1)
|
| 117 |
result["analysis"] = analysis_part.strip()
|
| 118 |
+
|
| 119 |
if "**CHANGES MADE:**" in remainder:
|
| 120 |
prompt_part, changes_part = remainder.split("**CHANGES MADE:**", 1)
|
| 121 |
result["optimized_prompt"] = prompt_part.strip()
|
| 122 |
result["changes"] = changes_part.strip()
|
| 123 |
else:
|
| 124 |
result["optimized_prompt"] = remainder.strip()
|
| 125 |
+
|
| 126 |
if not result["optimized_prompt"]:
|
| 127 |
result["optimized_prompt"] = raw_response
|
| 128 |
result["analysis"] = "Could not parse structured response."
|
| 129 |
+
|
| 130 |
return result
|
| 131 |
|
| 132 |
|
|
|
|
| 138 |
"",
|
| 139 |
""
|
| 140 |
)
|
| 141 |
+
|
| 142 |
try:
|
| 143 |
result = optimize_prompt(prompt, context)
|
| 144 |
+
|
| 145 |
+
analysis = "### 🔍 Analysis\n\n" + result['analysis']
|
|
|
|
|
|
|
| 146 |
optimized = result['optimized_prompt']
|
| 147 |
+
changes = "### 📝 Changes Made\n\n" + result['changes']
|
| 148 |
+
|
|
|
|
|
|
|
| 149 |
return analysis, optimized, changes
|
| 150 |
+
|
| 151 |
except Exception as e:
|
| 152 |
return (
|
| 153 |
f"❌ Error: {str(e)}",
|
|
|
|
| 174 |
with demo:
|
| 175 |
gr.Markdown("""
|
| 176 |
# ✨ Prompt Optimizer
|
| 177 |
+
|
| 178 |
Transform basic prompts into powerful, well-structured instructions that get better results from AI.
|
| 179 |
+
|
| 180 |
**How it works:** Enter your rough prompt → AI analyzes weaknesses → Returns an optimized version with explanations.
|
| 181 |
+
|
| 182 |
**Optimization Techniques Applied:**
|
| 183 |
- 🎯 Clarity & Specificity
|
| 184 |
- 🎭 Role/Persona Framing
|
|
|
|
| 186 |
- 🚧 Constraints & Guardrails
|
| 187 |
- 🔢 Task Decomposition
|
| 188 |
""")
|
| 189 |
+
|
| 190 |
with gr.Row():
|
| 191 |
with gr.Column(scale=1):
|
| 192 |
gr.Markdown("### 📝 Input")
|
| 193 |
+
|
| 194 |
prompt_input = gr.Textbox(
|
| 195 |
label="Your Prompt",
|
| 196 |
+
placeholder="Enter the prompt you want to optimize...\n\nExample: 'write about dogs'",
|
|
|
|
|
|
|
| 197 |
lines=4
|
| 198 |
)
|
| 199 |
+
|
| 200 |
context_input = gr.Textbox(
|
| 201 |
label="Additional Context (Optional)",
|
| 202 |
+
placeholder="Any extra context about how you'll use this prompt...\n\nExample: 'For a children's educational website'",
|
|
|
|
|
|
|
| 203 |
lines=2
|
| 204 |
)
|
| 205 |
+
|
| 206 |
optimize_btn = gr.Button("✨ Optimize Prompt", variant="primary")
|
| 207 |
+
|
| 208 |
gr.Markdown("### 💡 Example Prompts")
|
| 209 |
gr.Examples(
|
| 210 |
examples=EXAMPLES,
|
| 211 |
inputs=[prompt_input, context_input],
|
| 212 |
label=""
|
| 213 |
)
|
| 214 |
+
|
| 215 |
with gr.Column(scale=1):
|
| 216 |
gr.Markdown("### 🎯 Results")
|
| 217 |
+
|
| 218 |
analysis_output = gr.Markdown(label="Analysis")
|
| 219 |
+
|
| 220 |
optimized_output = gr.Textbox(
|
| 221 |
label="Optimized Prompt (Ready to Copy)",
|
| 222 |
lines=10,
|
| 223 |
show_copy_button=True,
|
| 224 |
interactive=False
|
| 225 |
)
|
| 226 |
+
|
| 227 |
changes_output = gr.Markdown(label="Changes Made")
|
| 228 |
+
|
| 229 |
optimize_btn.click(
|
| 230 |
fn=process_optimization,
|
| 231 |
inputs=[prompt_input, context_input],
|
| 232 |
outputs=[analysis_output, optimized_output, changes_output]
|
| 233 |
)
|
| 234 |
+
|
| 235 |
with gr.Accordion("📚 Prompt Engineering Tips", open=False):
|
| 236 |
gr.Markdown("""
|
| 237 |
### Best Practices for Writing Prompts
|
| 238 |
+
|
| 239 |
**1. Be Specific**
|
| 240 |
- ❌ "Write about history"
|
| 241 |
- ✅ "Write a 500-word overview of the causes of World War I, focusing on the alliance system and nationalism"
|
| 242 |
+
|
| 243 |
**2. Define the Output Format**
|
| 244 |
- ❌ "Give me some ideas"
|
| 245 |
- ✅ "Give me 5 ideas as a numbered list, with a one-sentence explanation for each"
|
| 246 |
+
|
| 247 |
**3. Set the Role/Persona**
|
| 248 |
- ❌ "Explain machine learning"
|
| 249 |
- ✅ "You are a computer science professor. Explain machine learning to a first-year undergraduate student"
|
| 250 |
+
|
| 251 |
**4. Add Constraints**
|
| 252 |
- ❌ "Write a story"
|
| 253 |
- ✅ "Write a 300-word short story set in Tokyo, featuring a detective, with a surprise ending. Avoid clichés."
|
| 254 |
+
|
| 255 |
**5. Break Down Complex Tasks**
|
| 256 |
- ❌ "Analyze this data and give recommendations"
|
| 257 |
- ✅ "1) Summarize the key trends in the data. 2) Identify the top 3 issues. 3) Provide actionable recommendations for each issue."
|
| 258 |
+
|
| 259 |
### Resources
|
| 260 |
- [OpenAI Prompt Engineering Guide](https://platform.openai.com/docs/guides/prompt-engineering)
|
| 261 |
- [Anthropic Prompt Engineering](https://docs.anthropic.com/claude/docs/prompt-engineering)
|
| 262 |
""")
|
| 263 |
+
|
| 264 |
with gr.Accordion("🔧 Technical Details", open=False):
|
| 265 |
+
gr.Markdown("""
|
| 266 |
| Component | Details |
|
| 267 |
|-----------|---------|
|
| 268 |
| **LLM Backend** | Groq API |
|