LLM-PROJECT / app.py
zephO-O's picture
Update app.py
120595f verified
Raw
History Blame Contribute Delete
6.57 kB
import os
from groq import Groq
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
SYSTEM_PROMPTS = {
"πŸ“– Explain": """
You are a friendly, patient study tutor. Your job is to explain any topic
clearly to a student who is hearing it for the first time.
Rules:
- Use simple everyday language. Avoid jargon unless you define it immediately.
- Break the explanation into short paragraphs.
- Use a real-world analogy to make the concept concrete.
- End with one "Key takeaway" sentence in bold.
- Keep the total response under 300 words.
""",
"πŸ§ͺ Quiz Me": """
You are a quiz master helping a student test their understanding.
When given a topic, generate exactly 5 multiple-choice questions. Format:
Q1. [Question]
A) ... B) ... C) ... D) ...
βœ… Answer: [Letter] β€” [Brief explanation]
Rules:
- Questions should cover different aspects of the topic.
- Only one option should be clearly correct.
- The explanation after the answer must be one sentence.
- Do not repeat options across questions.
""",
"πŸ“ Summarise": """
You are an expert note-taker. Summarise the given topic or text for a student
who needs to revise quickly.
Format your summary as:
β€’ 3–5 bullet points covering the main ideas
β€’ One "Remember this" box at the end (a single memorable fact or formula)
Rules:
- Every bullet must be one concise sentence.
- Use student-friendly language.
- Do not add padding or filler phrases like "In conclusion...".
""",
"πŸ—‚οΈ Flashcards": """
You are a flashcard generator. Given a topic, produce 6 study flashcards.
Format each card as:
FRONT: [Term or concept]
BACK: [Clear, concise definition or explanation β€” max 2 sentences]
Rules:
- Cover a variety of sub-topics within the given subject.
- Keep BACK answers short enough to memorise in one reading.
- Number each card (Card 1, Card 2, …).
""",
"πŸ” Ask a Doubt": """
You are a helpful teaching assistant. Answer the student's specific question
directly and accurately.
Rules:
- Answer only what is asked. Do not pad with unrelated information.
- If the question has a common misconception, address it briefly.
- Use examples or analogies if they make the answer clearer.
- Keep the response under 200 words.
""",
}
def study_assistant(topic: str, mode: str) -> str:
"""
Sends a prompt to Groq and returns the response text.
Args:
topic: The student's question or topic to study.
mode: One of the keys in SYSTEM_PROMPTS (matches the dropdown).
Returns:
The model's response as a plain string.
"""
if not topic.strip():
return "⚠️ Please enter a topic or question first."
system_instruction = SYSTEM_PROMPTS.get(mode, SYSTEM_PROMPTS["πŸ“– Explain"])
try:
response = client.chat.completions.create(
model="llama-3.1-8b-instant", # Fast, free-tier Groq model
messages=[
{"role": "system", "content": system_instruction},
{"role": "user", "content": topic},
],
temperature=0.7, # Balanced creativity
max_tokens=1024, # Enough for flashcards / quiz output
)
return response.choices[0].message.content
except Exception as error:
return f"❌ API error: {error}\n\nCheck that your GROQ_API_KEY secret is set correctly."
import gradio as gr
with gr.Blocks(title="πŸ“š Personalized Study Assistant") as demo:
# ── Header ────────────────────────────────────────────────
gr.Markdown("""
# πŸ“š Personalized Study Assistant
*Powered by Groq (LLaMA 3.1) β€’ Built for ADYPU LLM Practicals*
Choose a study mode, enter your topic or question, and hit **Generate**.
""")
# ── Controls ──────────────────────────────────────────────
with gr.Row():
mode_selector = gr.Dropdown(
choices=list(SYSTEM_PROMPTS.keys()),
value="πŸ“– Explain",
label="Study Mode",
info="Pick how you want to interact with the material.",
)
topic_input = gr.Textbox(
label="Your topic or question",
placeholder="e.g. Newton's laws of motion | What is photosynthesis? | Explain recursion",
lines=2,
)
generate_btn = gr.Button("⚑ Generate", variant="primary")
# ── Output ────────────────────────────────────────────────
output_box = gr.Textbox(
label="Study Assistant Response",
lines=18,
)
# ── Mode description cards ────────────────────────────────
with gr.Accordion("ℹ️ What does each mode do?", open=False):
gr.Markdown("""
| Mode | What it does |
|------|-------------|
| πŸ“– Explain | Breaks down any topic using simple language + a real-world analogy |
| πŸ§ͺ Quiz Me | Generates 5 multiple-choice questions with answers & explanations |
| πŸ“ Summarise | Bullet-point revision notes + a key fact to remember |
| πŸ—‚οΈ Flashcards | 6 FRONT/BACK flashcards ready to memorise |
| πŸ” Ask a Doubt | Direct answer to your specific question |
""")
# ── Example buttons ───────────────────────────────────────
gr.Examples(
examples=[
["Photosynthesis", "πŸ“– Explain"],
["Newton's Laws of Motion", "πŸ§ͺ Quiz Me"],
["The Water Cycle", "πŸ“ Summarise"],
["Machine Learning", "πŸ—‚οΈ Flashcards"],
["What is the difference between RAM and ROM?", "πŸ” Ask a Doubt"],
],
inputs=[topic_input, mode_selector],
label="Try an example",
)
# ── Wire up the button ────────────────────────────────────
generate_btn.click(
fn=study_assistant,
inputs=[topic_input, mode_selector],
outputs=output_box,
)
# Also trigger on Enter key in the text box
topic_input.submit(
fn=study_assistant,
inputs=[topic_input, mode_selector],
outputs=output_box,
)
demo.launch(server_name="0.0.0.0", server_port=7860)