CoolFace
Apppublic

eefree02/ECE618Project5

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
app.py329 linesDownload Raw Back to root
1"""2Engineering Chatbot Template3Complete all TODO sections to customize the chatbot!4"""5from huggingface_hub import InferenceClient6import gradio as gr7import os8 9# %%10# =============================================11# CONFIGURATION - Complete TODOs 1-412# =============================================13 14# TODO 1: Add HuggingFace API key here15# Get it from: https://huggingface.co/settings/tokens16API_KEY = os.environ.get("API_KEY")  # Replace with API key17 18# TODO 2: Choose model from the provided model list19MODEL = "HuggingFaceH4/zephyr-7b-beta"20 21# TODO 3: Customize chatbot's domain and role22CHATBOT_DOMAIN = "Electrical and Computer Engineering Education"  # Example: "ECE", "Mecanical", "Civil"23CHATBOT_ROLE = "provide educational engineering information about the electrical and computer engineering domain"  # What does bot do?24 25# TODO 4: Add guidelines (keep the existing ones and add 2-3 more)26CUSTOM_GUIDELINES = [27    "Be accurate and evidence-based",28    "Use clear, simple language",29    "Explain engineering terms when used",30    "Focus only on electrical and computer engineering topics",31    "Reference and cite all sources used",32    "Provide electrical and computer engineering related formulas and definitions", 33]34 35 36# %%37# Build system prompt from customizations38# Default to Beginner mode39SYSTEM_PROMPT = f"""You are a helpful AI Engineer specialized in {CHATBOT_DOMAIN}.40 41Your role is to {CHATBOT_ROLE} in simple terms for beginners. Provide references and citations to sources.42 43Guidelines:44{chr(10).join(f'- {guideline}' for guideline in CUSTOM_GUIDELINES)}45 46Remember: You provide educational information only, not critical professional advice."""47 48# Model parameters (you can adjust these if needed)49PARAMS = {50    'max_tokens': 500,51    'temperature': 0.7,52    'top_p': 0.9,53}54 55# Initialize HuggingFace client56client = InferenceClient(model=MODEL, token=API_KEY)57 58# %%59# =============================================60# CONVERSATION MEMORY61# =============================================62 63conversation_history = []64 65 66# %%67# =============================================68# CORE FUNCTIONS69# =============================================70 71def chat(user_message):72    73    # Use the slider values74    # PARAMS['temperature'] = temperature75    # PARAMS['max_tokens'] = max_length76 77    """Main chat function with conversation memory"""78 79    if not user_message.strip():80        return "Please ask a question!"81 82    # Add user message to history83    conversation_history.append({84        'role': 'user',85        'content': user_message86    })87 88    # Keep last 20 messages to avoid token limits89    recent_history = conversation_history[-20:]90    messages = [91        {'role': 'system', 'content': SYSTEM_PROMPT}92    ] + recent_history93 94    # Get AI response95    try:96        response = client.chat.completions.create(97            model=MODEL,98            messages=messages,99            max_tokens=PARAMS['max_tokens'],100            temperature=PARAMS['temperature'],101            top_p=PARAMS['top_p']102        )103 104        answer = response.choices[0].message.content105 106        # Add assistant response to history107        conversation_history.append({108            'role': 'assistant',109            'content': answer110        })111 112        # Add disclaimer113        disclaimer = "\n\n" + "─"*50 + "\n**Disclaimer:** Educational information only. Always consult professionals for engineering advice."114 115        return answer + disclaimer116 117    except Exception as e:118        error_msg = f"Error: {str(e)}\n\n"119 120        if "401" in str(e) or "unauthorized" in str(e).lower():121            error_msg += "Check your API key at: https://huggingface.co/settings/tokens"122        elif "404" in str(e):123            error_msg += "Model not found. Make sure you copied the model name correctly."124        elif "429" in str(e):125            error_msg += "Too many requests. Wait a moment and try again."126        elif "403" in str(e):127            error_msg += "This model requires access. Choose a different model from the free list."128        else:129            error_msg += "Check your internet connection and API key."130 131        return error_msg132 133# %%134def clear_conversation():135    """Clear conversation history"""136    global conversation_history137    conversation_history = []138    return "", "Conversation cleared! Start fresh."139 140# %%141# Feature 1: Switch between beginner and professional modes142current_mode = "beginner"  # default143 144def switch_mode(mode):145    """Switch between beginner and professional mode"""146    global current_mode, SYSTEM_PROMPT147    current_mode = mode148    149    if mode == "beginner":150        SYSTEM_PROMPT = f"""You are a helpful AI Engineer specialized in {CHATBOT_DOMAIN}.151 152        Your role is to {CHATBOT_ROLE} in simple terms for beginners. Provide references and citations to sources.153 154        Guidelines:155        {chr(10).join(f'- {guideline}' for guideline in CUSTOM_GUIDELINES)}156 157        Remember: You provide educational information only, not critical professional advice."""158    else:  # professional mode159        SYSTEM_PROMPT = f"""You are a helpful AI Engineer specialized in {CHATBOT_DOMAIN}.160 161        Your role is to {CHATBOT_ROLE} in detailed terms for advanced professionals. Provide references and citations to sources.162 163        Guidelines:164        {chr(10).join(f'- {guideline}' for guideline in CUSTOM_GUIDELINES)}165 166        Remember: You provide educational information only, not critical professional advice."""167    return f"Switched to {mode} mode"168 169 170# %%171# Feature 3: Export conversation to a .txt file172def export_conversation():173    """Export chat history to text file"""174    if not conversation_history:175        return "No conversation to export!"176    177    text = ""178    for msg in conversation_history:179        role = msg['role'].upper()180        content = msg['content']181        text += f"{role}:\n{content}\n\n" + "─"*50 + "\n\n"182    183    # Save to file184    with open("conversation_export.txt", "w") as f:185        f.write(text)186    187    return "Exported to conversation_export.txt"188 189# %%190# =============================================191# GRADIO INTERFACE - Complete TODOs 5-8192# =============================================193 194with gr.Blocks(title="... Engineering Chatbot") as app:195 196    # TODO 5: Customize header197    gr.Markdown(f"""198    # Electrical and Computer Engineering Chatbot199    ### Provides educational engineering information about the electrical and computer domain.200 201    **Domain:** {CHATBOT_DOMAIN}202    **Model:** {MODEL}203    """)204 205    # Main chat interface206    with gr.Row():207        with gr.Column(scale=2):208            question = gr.Textbox(209                label="Your Question",210                placeholder=f"Ask anything about {CHATBOT_DOMAIN.lower()}...",211                lines=3212            )213 214            with gr.Row():215                submit_btn = gr.Button("Ask", variant="primary", size="lg")216                clear_btn = gr.Button("Clear", size="lg")217 218        with gr.Column(scale=3):219            response = gr.Textbox(220                label="AI Response",221                lines=15,222                interactive=False223            )224 225    # TODO 6: Add 5 example questions relevant to YOUR domain226    gr.Examples(227        examples=[228            "How does a transformer work in power distribution?",229            "What is Ohm's Law?",230            "What is the difference between an OR and an AND logic gate?",231            "What is the purpose of transistors in electronic circuits?",232            "What is the definition of electrical current?",233        ],234        inputs=question,235        label="Try these examples:"236    )237 238    # TODO 7: Fill in the About section239    with gr.Accordion("ℹAbout This Chatbot", open=False):240        gr.Markdown(f"""241        ### About242        The purpose of this Chatbot is to accurately answer questions relating to the specific domain of electrical and computer engineering. The use of this chatbot is for educational purposes only and should be utilized as a tool to enhance the user's learning experience.243 244        ### Features245        - Multiple Modes: Beginner and Professional246        - Example Library of Preloaded Questions247        - Export Conversation to a .txt file248        - Conversation memory (remembers context)249        - Clear and educational responses250        - Source Referencing251 252        ### Technical Details253        - **Model:** {MODEL}254        - **Domain:** {CHATBOT_DOMAIN}255        - **Temperature:** {PARAMS['temperature']}256        - **Max Response Length:** {PARAMS['max_tokens']} tokens257 258        ### Important Disclaimers259        - This is for educational purposes only260        - Not a substitute for professional engineering advice261        - Always consult qualified electrical and computer engineering professionals262        - Do not use as a source to make engineering decisions263 264        ### Creator Information265        - **Name:** Ella Freeman266        - **Course:** Engineering AI267        - **Date:** 12/1/2025268        - **University:** University of Louisville269        """)270 271    # TODO 8: Add your additional notes or instructions272    with gr.Accordion("How to Use", open=False):273        gr.Markdown("""274        ### How to Use This Chatbot275 276        1. **Ask a Question:** Type your question in the text box277        2. **Get Response:** Click "Ask" button or press Enter278        3. **Continue Conversation:** Ask follow-up questions (bot remembers context)279        4. **Start Fresh:** Click "Clear" to reset the conversation280 281        ### Tips for Best Results282        - Be specific in your questions283        - Ask one question at a time284        - Use follow-up questions for more details285        - Make sure question relates to electrical and computer engineering286        - Be clear about the purpose of your question287 288        ### What You Can Ask About289        - Circuit Analysis290        - Electromagnetic Waves291        - Signal Processing292        - Electronics          293        - Power Systems294        """)295 296    # Feature 1: Add user and professional modes297    mode_selector = gr.Radio(298        choices=["beginner", "professional"],299        value="beginner",300        label="Mode"301    )302 303    # Feature 2: Add Temperature and Length sliders304    # with gr.Accordion("Advanced Settings", open=False):305        # temp_slider = gr.Slider(0, 1, value=0.7, label="Temperature")306        # length_slider = gr.Slider(100, 1000, value=300, step=50, label="Max Length")307 308    # Feature 2: Temperature and Length Sliders309    # submit_btn.click(chat, inputs=[question, temp_slider, length_slider], outputs=response)310 311 312    # Connect buttons to functions313    submit_btn.click(chat, inputs=question, outputs=response)314    clear_btn.click(clear_conversation, outputs=[question, response])315    question.submit(chat, inputs=question, outputs=response)316 317    # Feature 1: Switch Mode Button318    mode_status = gr.Textbox(label="Mode Status")319    mode_selector.change(switch_mode, inputs=mode_selector, outputs=mode_status)320 321    # Feature 3: Export Conversation Button322    export_btn = gr.Button("Export Conversation")323    export_status = gr.Textbox(label="Export Status")324    export_btn.click(export_conversation, outputs=export_status)325 326 327if __name__ == "__main__":328    app.launch()329