Nav772 commited on
Commit
8ecafd5
·
verified ·
1 Parent(s): 8d0dbce

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +13 -62
app.py CHANGED
@@ -2,11 +2,6 @@ import gradio as gr
2
  import os
3
  from groq import Groq
4
 
5
- # =============================================================================
6
- # Prompt Optimizer
7
- # =============================================================================
8
-
9
- # Initialize Groq client
10
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
11
  if not GROQ_API_KEY:
12
  raise ValueError("GROQ_API_KEY environment variable not set")
@@ -16,7 +11,6 @@ MODEL = "llama-3.3-70b-versatile"
16
 
17
  print(f"✅ Groq client initialized with model: {MODEL}")
18
 
19
- # ----- Optimizer System Prompt -----
20
  OPTIMIZER_SYSTEM_PROMPT = """You are an expert prompt engineer. Your task is to analyze and optimize user prompts to get better results from AI language models.
21
 
22
  When given a prompt, you will:
@@ -74,7 +68,6 @@ You MUST respond in this exact format:
74
 
75
 
76
  def optimize_prompt(user_prompt: str, context: str = "") -> dict:
77
- """Optimize a user's prompt using LLM analysis."""
78
  if not user_prompt.strip():
79
  return {
80
  "analysis": "No prompt provided.",
@@ -131,32 +124,19 @@ def optimize_prompt(user_prompt: str, context: str = "") -> dict:
131
 
132
 
133
  def process_optimization(prompt: str, context: str) -> tuple:
134
- """Process the optimization request and return formatted outputs."""
135
  if not prompt.strip():
136
- return (
137
- "⚠️ Please enter a prompt to optimize.",
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)}",
154
- "",
155
- ""
156
- )
157
 
158
 
159
- # ----- Example Prompts -----
160
  EXAMPLES = [
161
  ["write about dogs", ""],
162
  ["help me with my code", ""],
@@ -168,7 +148,6 @@ EXAMPLES = [
168
  ["help me prepare for interview", "Software engineering position at Google"],
169
  ]
170
 
171
- # ----- Gradio Interface -----
172
  demo = gr.Blocks()
173
 
174
  with demo:
@@ -177,6 +156,8 @@ with demo:
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:**
@@ -185,47 +166,34 @@ with demo:
185
  - 📋 Output Format Instructions
186
  - 🚧 Constraints & Guardrails
187
  - 🔢 Task Decomposition
188
-
189
- [![Powered by Groq](https://console.groq.com/powered-by-groq-dark.svg)](https://groq.com)
190
  """)
191
 
192
  with gr.Row():
193
  with gr.Column(scale=1):
194
  gr.Markdown("### 📝 Input")
195
-
196
  prompt_input = gr.Textbox(
197
  label="Your Prompt",
198
  placeholder="Enter the prompt you want to optimize...\n\nExample: 'write about dogs'",
199
  lines=4
200
  )
201
-
202
  context_input = gr.Textbox(
203
  label="Additional Context (Optional)",
204
- placeholder="Any extra context about how you'll use this prompt...\n\nExample: 'For a children's educational website'",
205
  lines=2
206
  )
207
-
208
  optimize_btn = gr.Button("✨ Optimize Prompt", variant="primary")
209
-
210
  gr.Markdown("### 💡 Example Prompts")
211
- gr.Examples(
212
- examples=EXAMPLES,
213
- inputs=[prompt_input, context_input],
214
- label=""
215
- )
216
 
217
  with gr.Column(scale=1):
218
  gr.Markdown("### 🎯 Results")
219
-
220
  analysis_output = gr.Markdown(label="Analysis")
221
-
222
  optimized_output = gr.Textbox(
223
  label="Optimized Prompt (Ready to Copy)",
224
  lines=10,
225
  show_copy_button=True,
226
  interactive=False
227
  )
228
-
229
  changes_output = gr.Markdown(label="Changes Made")
230
 
231
  optimize_btn.click(
@@ -238,31 +206,16 @@ with demo:
238
  gr.Markdown("""
239
  ### Best Practices for Writing Prompts
240
 
241
- **1. Be Specific**
242
- - ❌ "Write about history"
243
- - ✅ "Write a 500-word overview of the causes of World War I, focusing on the alliance system and nationalism"
244
-
245
- **2. Define the Output Format**
246
- - ❌ "Give me some ideas"
247
- - ✅ "Give me 5 ideas as a numbered list, with a one-sentence explanation for each"
248
 
249
- **3. Set the Role/Persona**
250
- - ❌ "Explain machine learning"
251
- - ✅ "You are a computer science professor. Explain machine learning to a first-year undergraduate student"
252
 
253
- **4. Add Constraints**
254
- - ❌ "Write a story"
255
- - ✅ "Write a 300-word short story set in Tokyo, featuring a detective, with a surprise ending. Avoid clichés."
256
 
257
- **5. Break Down Complex Tasks**
258
- - ❌ "Analyze this data and give recommendations"
259
- - ✅ "1) Summarize the key trends in the data. 2) Identify the top 3 issues. 3) Provide actionable recommendations for each issue."
260
 
261
- ### Resources
262
- - [OpenAI Prompt Engineering Guide](https://platform.openai.com/docs/guides/prompt-engineering)
263
- - [Anthropic Prompt Engineering](https://docs.anthropic.com/claude/docs/prompt-engineering)
264
- """
265
- )
266
 
267
  with gr.Accordion("🔧 Technical Details", open=False):
268
  gr.Markdown("""
@@ -271,9 +224,7 @@ with demo:
271
  | **LLM Backend** | Groq API |
272
  | **Model** | Llama 3.3 70B Versatile |
273
  | **Optimization Techniques** | 5 (Clarity, Role, Format, Constraints, Decomposition) |
274
- | **Response Parsing** | Structured sections (Analysis, Optimized, Changes) |
275
- """
276
- )
277
 
278
  if __name__ == "__main__":
279
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
2
  import os
3
  from groq import Groq
4
 
 
 
 
 
 
5
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
6
  if not GROQ_API_KEY:
7
  raise ValueError("GROQ_API_KEY environment variable not set")
 
11
 
12
  print(f"✅ Groq client initialized with model: {MODEL}")
13
 
 
14
  OPTIMIZER_SYSTEM_PROMPT = """You are an expert prompt engineer. Your task is to analyze and optimize user prompts to get better results from AI language models.
15
 
16
  When given a prompt, you will:
 
68
 
69
 
70
  def optimize_prompt(user_prompt: str, context: str = "") -> dict:
 
71
  if not user_prompt.strip():
72
  return {
73
  "analysis": "No prompt provided.",
 
124
 
125
 
126
  def process_optimization(prompt: str, context: str) -> tuple:
 
127
  if not prompt.strip():
128
+ return ("⚠️ Please enter a prompt to optimize.", "", "")
 
 
 
 
129
 
130
  try:
131
  result = optimize_prompt(prompt, context)
 
132
  analysis = "### 🔍 Analysis\n\n" + result['analysis']
133
  optimized = result['optimized_prompt']
134
  changes = "### 📝 Changes Made\n\n" + result['changes']
 
135
  return analysis, optimized, changes
 
136
  except Exception as e:
137
+ return (f"❌ Error: {str(e)}", "", "")
 
 
 
 
138
 
139
 
 
140
  EXAMPLES = [
141
  ["write about dogs", ""],
142
  ["help me with my code", ""],
 
148
  ["help me prepare for interview", "Software engineering position at Google"],
149
  ]
150
 
 
151
  demo = gr.Blocks()
152
 
153
  with demo:
 
156
 
157
  Transform basic prompts into powerful, well-structured instructions that get better results from AI.
158
 
159
+ [![Powered by Groq](https://console.groq.com/powered-by-groq-dark.svg)](https://groq.com)
160
+
161
  **How it works:** Enter your rough prompt → AI analyzes weaknesses → Returns an optimized version with explanations.
162
 
163
  **Optimization Techniques Applied:**
 
166
  - 📋 Output Format Instructions
167
  - 🚧 Constraints & Guardrails
168
  - 🔢 Task Decomposition
 
 
169
  """)
170
 
171
  with gr.Row():
172
  with gr.Column(scale=1):
173
  gr.Markdown("### 📝 Input")
 
174
  prompt_input = gr.Textbox(
175
  label="Your Prompt",
176
  placeholder="Enter the prompt you want to optimize...\n\nExample: 'write about dogs'",
177
  lines=4
178
  )
 
179
  context_input = gr.Textbox(
180
  label="Additional Context (Optional)",
181
+ placeholder="Any extra context about how you'll use this prompt...",
182
  lines=2
183
  )
 
184
  optimize_btn = gr.Button("✨ Optimize Prompt", variant="primary")
 
185
  gr.Markdown("### 💡 Example Prompts")
186
+ gr.Examples(examples=EXAMPLES, inputs=[prompt_input, context_input], label="")
 
 
 
 
187
 
188
  with gr.Column(scale=1):
189
  gr.Markdown("### 🎯 Results")
 
190
  analysis_output = gr.Markdown(label="Analysis")
 
191
  optimized_output = gr.Textbox(
192
  label="Optimized Prompt (Ready to Copy)",
193
  lines=10,
194
  show_copy_button=True,
195
  interactive=False
196
  )
 
197
  changes_output = gr.Markdown(label="Changes Made")
198
 
199
  optimize_btn.click(
 
206
  gr.Markdown("""
207
  ### Best Practices for Writing Prompts
208
 
209
+ **1. Be Specific** - ❌ "Write about history" → ✅ "Write a 500-word overview of the causes of World War I"
 
 
 
 
 
 
210
 
211
+ **2. Define the Output Format** - ❌ "Give me some ideas" → ✅ "Give me 5 ideas as a numbered list"
 
 
212
 
213
+ **3. Set the Role/Persona** - ❌ "Explain machine learning" → ✅ "You are a CS professor. Explain ML to a first-year student"
 
 
214
 
215
+ **4. Add Constraints** - ❌ "Write a story" → ✅ "Write a 300-word short story set in Tokyo with a surprise ending"
 
 
216
 
217
+ **5. Break Down Complex Tasks** - ❌ "Analyze this data" → ✅ "1) Summarize trends. 2) Identify issues. 3) Provide recommendations."
218
+ """)
 
 
 
219
 
220
  with gr.Accordion("🔧 Technical Details", open=False):
221
  gr.Markdown("""
 
224
  | **LLM Backend** | Groq API |
225
  | **Model** | Llama 3.3 70B Versatile |
226
  | **Optimization Techniques** | 5 (Clarity, Role, Format, Constraints, Decomposition) |
227
+ """)
 
 
228
 
229
  if __name__ == "__main__":
230
  demo.launch(server_name="0.0.0.0", server_port=7860)