Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 11 |
-
llama_model = None
|
| 12 |
-
llama_tokenizer = None
|
| 13 |
|
| 14 |
def call_openai(prompt):
|
| 15 |
-
"""Call OpenAI
|
| 16 |
try:
|
| 17 |
-
# Detailed system prompt for prompt coaching rather than answering
|
| 18 |
system_prompt = """You are a helpful Prompt Interpretation Coach.
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 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"
|
| 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 |
-
"""
|
| 65 |
-
global
|
| 66 |
-
if
|
| 67 |
try:
|
| 68 |
-
|
| 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"
|
| 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
|
| 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'
|
| 127 |
-
|
| 128 |
-
#
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 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 |
-
|
| 148 |
-
|
| 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 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
elif "auth" in error_str or "api key" in error_str:
|
| 157 |
return "❌ Invalid or missing OpenAI API key."
|
| 158 |
-
|
| 159 |
-
return prefix + f"Unexpected error: {str(e)}\n\nFalling back to LLaMA model...\n\n" + call_llama(prompt)
|
| 160 |
|
| 161 |
-
#
|
| 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 |
-
#
|
| 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 |
Learning to craft clear, specific prompts helps you:
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 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()
|
|
|
|
|
|