tjido commited on
Commit
f66afc7
·
verified ·
1 Parent(s): 4a89df5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -186
app.py CHANGED
@@ -1,164 +1,79 @@
1
  import os
2
  import openai
3
  import gradio as gr
4
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
5
- import torch
6
 
7
  # Load OpenAI API key
8
  openai.api_key = os.getenv("OPENAI_API_KEY")
9
 
10
- # Try to define the fallback model ahead of time so it's ready
11
- llama_model = None
12
- llama_tokenizer = None
13
 
14
  def call_openai(prompt):
15
- """Call OpenAI API to analyze the prompt rather than just answering it."""
16
  try:
17
- # Detailed system prompt for prompt coaching rather than answering
18
  system_prompt = """You are a helpful Prompt Interpretation Coach.
19
-
20
- Your goal is to:
21
- 1. Explain how an AI would interpret their prompt (not to answer it directly)
22
- 2. Highlight any ambiguities or potential misunderstandings in their prompt
23
- 3. Suggest improvements to make their prompt clearer and more effective
24
- 4. Offer 1-2 alternative phrasings that might work better
25
-
26
- EXTREMELY IMPORTANT RULES:
27
- - NEVER actually execute or fulfill the student's request
28
- - For example, if they ask "Write a poem about AI," DO NOT write a poem - instead analyze how AI would interpret that prompt
29
- - Begin your response with "PROMPT ANALYSIS:" to reinforce you are analyzing, not answering
30
- - Keep your language and themes appropriate for high school students and young kids
31
- - Avoid any harmful, inappropriate, or mature content
32
- - Focus on educational value and critical thinking skills
33
- - Be encouraging and constructive in your feedback
34
- - Keep responses concise (max 4-5 short paragraphs)
35
- - If the prompt asks for potentially harmful content, gently redirect without repeating harmful elements
36
- """
37
-
38
- # Updated to use current OpenAI client library
39
  client = openai.OpenAI(api_key=openai.api_key)
40
  response = client.chat.completions.create(
41
  model="gpt-3.5-turbo",
42
  messages=[
43
  {"role": "system", "content": system_prompt},
44
- {"role": "user", "content": f"Provide ONLY an analysis of this prompt: \"{prompt}\". DO NOT fulfill the request, only analyze it."}
45
- ],
46
- temperature=0.7,
47
- max_tokens=350
48
- )
49
- return response.choices[0].message.content.strip()
50
- except AttributeError:
51
- # Fallback for older version of OpenAI client
52
- response = openai.ChatCompletion.create(
53
- model="gpt-3.5-turbo",
54
- messages=[
55
- {"role": "system", "content": system_prompt},
56
- {"role": "user", "content": f"Analyze this prompt: \"{prompt}\""}
57
  ],
58
  temperature=0.7,
59
  max_tokens=350
60
  )
61
  return response.choices[0].message.content.strip()
62
 
 
 
 
63
  def call_llama(prompt):
64
- """Call LLaMA model to analyze the prompt rather than just answering it."""
65
- global llama_model, llama_tokenizer
66
- if llama_model is None or llama_tokenizer is None:
67
  try:
68
- llama_tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
69
- llama_model = AutoModelForCausalLM.from_pretrained(
70
- "meta-llama/Meta-Llama-3-8B-Instruct",
71
- torch_dtype=torch.float16,
72
- device_map="auto"
73
- )
74
  except Exception as e:
75
- return f"Failed to load LLaMA model: {str(e)}"
76
-
77
- try:
78
- # Create a more detailed prompt for LLaMA to analyze rather than answer
79
- full_prompt = f"""<|system|>
80
- You are a Prompt Interpretation Coach. Your ONLY job is to analyze how an AI would interpret the following prompt.
81
-
82
- EXTREMELY IMPORTANT RULES:
83
- 1. NEVER execute or fulfill the actual request in the prompt
84
- 2. ALWAYS start your response with "PROMPT ANALYSIS:" to emphasize you are analyzing
85
- 3. If the prompt says "Write a poem about AI" - DO NOT write a poem! Instead explain how an AI would interpret that request
86
- 4. Explain how an AI system would understand this prompt
87
- 5. Point out any unclear parts or potential misunderstandings
88
- 6. Suggest specific improvements to make the prompt more effective
89
- 7. Always keep content appropriate for young learners
90
- 8. Be encouraging and educational
91
-
92
- Keep your analysis concise (4-5 short paragraphs maximum).
93
- <|user|>
94
- ONLY analyze this prompt (DO NOT fulfill it): "{prompt}"
95
- <|assistant|>
96
- PROMPT ANALYSIS:
97
- """
98
-
99
- inputs = llama_tokenizer(full_prompt, return_tensors="pt")
100
- # Move to the device where the model is
101
- if torch.cuda.is_available():
102
- inputs = inputs.to("cuda")
103
- else:
104
- inputs = inputs.to(llama_model.device)
105
-
106
- outputs = llama_model.generate(
107
- **inputs,
108
- max_new_tokens=350,
109
- temperature=0.7,
110
- do_sample=True
111
- )
112
-
113
- generated_text = llama_tokenizer.decode(outputs[0], skip_special_tokens=True)
114
-
115
- # Extract just the assistant's response if possible
116
- if "<|assistant|>" in generated_text:
117
- return generated_text.split("<|assistant|>")[1].strip()
118
- return generated_text
119
- except Exception as e:
120
- return f"Error generating response with LLaMA: {str(e)}"
121
 
122
  def interpret_prompt(prompt):
123
- """Main function to interpret and analyze the prompt."""
124
- # Check if prompt is empty or too short
125
  if not prompt or len(prompt.strip()) < 3:
126
- return "Please enter a prompt to analyze. Try something like 'Write a poem about space' or 'Explain quantum physics simply'."
127
-
128
- # Content safety check - very basic implementation
129
- # A more robust implementation would use a dedicated content filter
130
- unsafe_terms = [
131
- "suicide", "self-harm", "kill", "porn", "naked", "nude", "sexual",
132
- "weapon", "bomb", "terrorist", "hack", "steal", "drug", "cocaine",
133
- "heroin", "illegal", "torrent", "pirate"
134
- ]
135
-
136
- # Check for unsafe content
137
- lower_prompt = prompt.lower()
138
- for term in unsafe_terms:
139
- if term in lower_prompt:
140
- return "⚠️ I notice your prompt might be asking for content that isn't appropriate for this educational tool. This coach is designed to help with academic and creative prompts. Could you try a different prompt related to school projects, creative writing, or learning concepts?"
141
-
142
- # Add a prefix to the output to further emphasize we're analyzing, not answering
143
  prefix = "AI Response:\n\n"
144
-
145
  try:
146
  response = call_openai(prompt)
147
- # If response starts with a common answer pattern instead of an analysis,
148
- # add an override message
149
- if any(response.lower().startswith(x) for x in ["here's a poem", "here is a poem", "once upon", "in a"]):
150
- return prefix + "⚠️ Note: It appears the AI tried to fulfill your request rather than analyze it. This is exactly why prompt engineering is important! Let me provide the correct analysis instead:\n\n" + call_openai("I need you to ONLY analyze this prompt and NOT fulfill it: " + prompt)
151
  return prefix + response
152
  except Exception as e:
153
- error_str = str(e).lower()
154
- if "rate limit" in error_str:
155
- return prefix + "[⚠️ OpenAI Rate Limit Hit — switching to LLaMA 3...]\n\n" + call_llama(prompt)
156
- elif "auth" in error_str or "api key" in error_str:
157
  return "❌ Invalid or missing OpenAI API key."
158
- else:
159
- return prefix + f"Unexpected error: {str(e)}\n\nFalling back to LLaMA model...\n\n" + call_llama(prompt)
160
 
161
- # Create a custom theme with better visuals
162
  custom_theme = gr.themes.Soft(
163
  primary_hue="indigo",
164
  secondary_hue="blue",
@@ -166,68 +81,59 @@ custom_theme = gr.themes.Soft(
166
  radius_size=gr.themes.sizes.radius_sm,
167
  )
168
 
169
- # Updated interface with improved visuals and clarity
170
- iface = gr.Interface(
171
- fn=interpret_prompt,
172
- inputs=gr.Textbox(
173
- lines=3,
174
- placeholder="Enter a prompt you'd like to analyze (e.g., 'Draw a star with turtle graphics')...",
175
- elem_id="prompt-input"
176
- ),
177
- outputs=gr.Textbox(
178
- label="Prompt Analysis & Coaching Tips",
179
- elem_id="analysis-output"
180
- ),
181
- title="🧠 Prompt Interpretation Coach",
182
- description="""## What is Prompt Interpretation Coach?
183
- This educational tool helps leaners learn **prompt engineering** by analyzing how AI systems interpret instructions.
184
-
185
- ### ⚙ How it works:
186
- * **Enter any prompt** you might give to an AI system
187
- * The coach **analyzes your prompt** instead of answering it
188
- * Learn what makes an effective prompt through real examples
189
- * Develop critical thinking about AI communication
190
-
191
- ### 📚 What you'll learn:
192
- * How AI would understand your instructions
193
- * Potential ambiguities or misunderstandings
194
- * Specific improvements for clearer prompts
195
- * Alternative phrasings that might work better
196
-
197
- *Try the examples below or enter your own prompt to start learning!*
198
- """,
199
- examples=[
200
- "Draw a star with turtle graphics",
201
- "Write a poem about AI",
202
- "Explain photosynthesis",
203
- "Plan my next trip",
204
- "Explain algebra like I'm 10"
205
- ],
206
- theme=custom_theme,
207
- elem_id="prompt-coach-interface"
208
- )
209
-
210
- # Add footer with attribution
211
- footer_html = """## ⌨️ Why Prompt Engineering Matters
 
 
 
212
  Learning to craft clear, specific prompts helps you:
 
 
 
213
 
214
- * **In education:** Get more accurate and helpful responses for homework and projects
215
- * **In research:** Direct AI to explore specific aspects of a topic
216
- * **In creativity:** Guide AI to help with your creative vision more effectively
217
- * **In coding:** Get more precise code suggestions and explanations
218
-
219
- **Made with love ❤️ for learners exploring the world of AI + code.**
220
- Created by Shingai Manjengwa, @tjido
221
- """
222
-
223
- # Create the Gradio app with the footer
224
- demo = gr.Blocks()
225
- with demo:
226
- # gr.Image("thumbnail.png", show_label=False, height=100, width=100)
227
- iface.render()
228
- gr.Markdown(footer_html)
229
 
230
  if __name__ == "__main__":
231
  demo.launch()
232
-
233
-
 
1
  import os
2
  import openai
3
  import gradio as gr
 
 
4
 
5
  # Load OpenAI API key
6
  openai.api_key = os.getenv("OPENAI_API_KEY")
7
 
8
+ llama_response = None # Global for LLaMA fallback model
 
 
9
 
10
  def call_openai(prompt):
11
+ """Call OpenAI GPT-3.5 to analyze the prompt."""
12
  try:
 
13
  system_prompt = """You are a helpful Prompt Interpretation Coach.
14
+
15
+ Your goal is to:
16
+ 1. Explain how an AI would interpret their prompt (not to answer it directly)
17
+ 2. Highlight any ambiguities or potential misunderstandings in their prompt
18
+ 3. Suggest improvements to make their prompt clearer and more effective
19
+ 4. Offer 1-2 alternative phrasings that might work better
20
+
21
+ EXTREMELY IMPORTANT RULES:
22
+ - NEVER actually execute or fulfill the student's request
23
+ - Begin your response with "PROMPT ANALYSIS:"
24
+ - Keep your tone appropriate for young learners
25
+ - Be clear, constructive, and concise (4-5 short paragraphs max)
26
+ """
 
 
 
 
 
 
 
27
  client = openai.OpenAI(api_key=openai.api_key)
28
  response = client.chat.completions.create(
29
  model="gpt-3.5-turbo",
30
  messages=[
31
  {"role": "system", "content": system_prompt},
32
+ {"role": "user", "content": f"Analyze this prompt ONLY: \"{prompt}\""}
 
 
 
 
 
 
 
 
 
 
 
 
33
  ],
34
  temperature=0.7,
35
  max_tokens=350
36
  )
37
  return response.choices[0].message.content.strip()
38
 
39
+ except Exception as e:
40
+ raise e # Bubble up to interpret_prompt
41
+
42
  def call_llama(prompt):
43
+ """Fallback to LLaMA hosted on Hugging Face via novita."""
44
+ global llama_response
45
+ if llama_response:
46
  try:
47
+ return llama_response(prompt)
 
 
 
 
 
48
  except Exception as e:
49
+ return f"⚠️ Error using LLaMA fallback: {str(e)}"
50
+ return "⚠️ LLaMA fallback not available. Please sign in with Hugging Face in the sidebar."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  def interpret_prompt(prompt):
53
+ """Main logic to analyze prompt quality and clarity."""
 
54
  if not prompt or len(prompt.strip()) < 3:
55
+ return "Please enter a prompt to analyze. Try something like 'Write a poem about space'."
56
+
57
+ # Simple safety check
58
+ unsafe_terms = ["suicide", "self-harm", "kill", "porn", "naked", "nude", "sexual", "weapon", "bomb", "terrorist", "hack", "steal", "drug", "cocaine", "heroin", "illegal", "torrent", "pirate"]
59
+ if any(term in prompt.lower() for term in unsafe_terms):
60
+ return "⚠️ That topic isn't appropriate for this tool. Try a school project, creative writing, or learning-related prompt."
61
+
 
 
 
 
 
 
 
 
 
 
62
  prefix = "AI Response:\n\n"
63
+
64
  try:
65
  response = call_openai(prompt)
66
+ if any(response.lower().startswith(x) for x in ["here's a poem", "once upon", "in a world", "roses are red"]):
67
+ return prefix + "⚠️ The AI started fulfilling your request. Let's try again with clearer instructions:\n\n" + call_openai("ONLY analyze this prompt: " + prompt)
 
 
68
  return prefix + response
69
  except Exception as e:
70
+ if "rate limit" in str(e).lower():
71
+ return prefix + "[⚠️ OpenAI Rate Limit Hit — switching to LLaMA fallback...]\n\n" + call_llama(prompt)
72
+ elif "auth" in str(e).lower() or "api key" in str(e).lower():
 
73
  return "❌ Invalid or missing OpenAI API key."
74
+ return prefix + f"⚠️ Unexpected error: {str(e)}\n\nSwitching to LLaMA fallback...\n\n" + call_llama(prompt)
 
75
 
76
+ # Theme
77
  custom_theme = gr.themes.Soft(
78
  primary_hue="indigo",
79
  secondary_hue="blue",
 
81
  radius_size=gr.themes.sizes.radius_sm,
82
  )
83
 
84
+ # Gradio UI
85
+ with gr.Blocks(theme=custom_theme, fill_height=True) as demo:
86
+ with gr.Sidebar():
87
+ gr.Markdown("## 🧠 Prompt Coach Settings")
88
+ gr.Markdown("OpenAI is used by default.\nIf rate-limited, fallback to LLaMA 3 via Hugging Face.")
89
+ login_button = gr.LoginButton("🔐 Sign in to use LLaMA fallback")
90
+
91
+ # Load LLaMA from Hugging Face using Novita provider
92
+ llama_response = gr.load(
93
+ "models/meta-llama/Meta-Llama-3-8B-Instruct",
94
+ provider="novita",
95
+ accept_token=login_button
96
+ )
97
+
98
+ gr.Interface(
99
+ fn=interpret_prompt,
100
+ inputs=gr.Textbox(
101
+ lines=3,
102
+ placeholder="e.g. 'Draw a star with turtle graphics'",
103
+ elem_id="prompt-input"
104
+ ),
105
+ outputs=gr.Textbox(
106
+ label="Prompt Analysis & Coaching Tips",
107
+ elem_id="analysis-output"
108
+ ),
109
+ title="🧠 Prompt Interpretation Coach",
110
+ description="""This tool helps students and creators understand how AI interprets their prompts — without actually answering them.
111
+
112
+ ### What you’ll learn:
113
+ - How AI interprets your instructions
114
+ - Ambiguities in your phrasing
115
+ - Better alternatives for clearer prompts
116
+ - Prompt engineering strategies for education
117
+
118
+ Try typing a school or creative prompt to begin!""",
119
+ examples=[
120
+ "Draw a star with turtle graphics",
121
+ "Write a poem about AI",
122
+ "Explain photosynthesis",
123
+ "Plan my next trip",
124
+ "Explain algebra like I'm 10"
125
+ ],
126
+ elem_id="prompt-coach-interface"
127
+ ).render()
128
+
129
+ gr.Markdown("""## ⌨️ Why Prompt Engineering Matters
130
  Learning to craft clear, specific prompts helps you:
131
+ - 📚 In education: Get more accurate responses
132
+ - 💡 In creativity: Express ideas more clearly
133
+ - 🧠 In learning: Improve critical thinking
134
 
135
+ **Created with ❤️ by Shingai Manjengwa | @tjido**
136
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
  if __name__ == "__main__":
139
  demo.launch()