import gradio as gr import os from groq import Groq # --- API Setup --- # Hugging Face Spaces reads secrets as Environment Variables api_key = os.getenv("EngGloss") # Check for key availability if not api_key: raise ValueError("API Key not found! Please go to your Space 'Settings' > 'Secrets' and create a secret named 'EngGloss' containing your Groq API key.") client = Groq(api_key=api_key) # --- The System Prompt --- system_prompt = """ You are EngGloss, an expert AI engineering tutor. Your goal is to explain technical engineering terms to students and beginners in a way that is structured, strictly factual, yet easy to understand. When given a term, you must output the response in the following Markdown format: ### 📖 Term: **💡 Simple Explanation:** **🍎 Real-World Analogy:** **⚙️ Real-World Engineering Applications:** Provide 3 distinct examples of how this term is applied in different engineering fields. Use this bullet format: * **[Field Name]:** Specific explanation of how the term is used here. (e.g., "Civil Engineering: Stress and Strain are calculated to ensure bridges can withstand the weight of traffic without collapsing.") * **[Field Name]:** Specific explanation of how the term is used here. * **[Field Name]:** Specific explanation of how the term is used here. **➗ Typical Formula:** Constraint: If the user input is NOT an engineering or scientific term, politely refuse and ask for a valid technical term. """ # --- Core Logic Function --- def explain_term(term): if not term.strip(): return "⚠️ Please enter an engineering term." try: chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": system_prompt, }, { "role": "user", "content": term, } ], # UPDATED MODEL NAME HERE model="llama-3.1-8b-instant", temperature=0.5, max_tokens=600, ) return chat_completion.choices[0].message.content except Exception as e: return f"❌ Error: {str(e)}" # --- Gradio UI --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# ⚙️ EngGloss: AI Engineering Tutor") gr.Markdown("Enter an engineering term below to get a structured, beginner-friendly explanation.") with gr.Row(): input_text = gr.Textbox( label="Enter Engineering Term", placeholder="e.g. Reynolds Number, Torque, Ohm's Law", lines=1 ) submit_btn = gr.Button("Explain Term", variant="primary") output_markdown = gr.Markdown(label="Explanation") # Connect the button to the function submit_btn.click(fn=explain_term, inputs=input_text, outputs=output_markdown) # Allow pressing "Enter" to submit as well input_text.submit(fn=explain_term, inputs=input_text, outputs=output_markdown) # Launch the app if __name__ == "__main__": demo.launch()