import streamlit as st import requests import wikipediaapi import os # For accessing environment variables # Securely fetch Hugging Face API key from environment variables HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY") if not HUGGINGFACE_API_KEY: st.error("⚠️ API Key Missing! Please add your Hugging Face API key as a secret in your Space settings.") st.stop() # Set up Wikipedia API USER_AGENT = "HistoricalChatbot/1.0 (Contact: your-email@example.com)" wiki_wiki = wikipediaapi.Wikipedia("en", headers={"User-Agent": USER_AGENT}) def get_wikipedia_summary(name): """Fetch summary from Wikipedia""" page = wiki_wiki.page(name) return page.summary if page.exists() else "Sorry, I couldn't find information on that historical figure." def chat_with_ai(person_name, user_input): """Query Hugging Face API for response""" context = get_wikipedia_summary(person_name) prompt = f"You are {person_name}. Based on this historical information: {context}\\n\\nUser: {user_input}\\n{person_name}:" API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.1" headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"} response = requests.post(API_URL, headers=headers, json={"inputs": prompt}) if response.status_code == 200: return response.json()[0]["generated_text"] else: return "I'm sorry, but I couldn't generate a response at this time." # Streamlit UI st.title("Educational Chatbot") mode = st.sidebar.selectbox("Select Chat Mode", ["Chat with Historical Figures", "Study with a Tutor"]) if mode == "Chat with Historical Figures": person_name = st.text_input("Enter the name of a historical figure:") if person_name: st.write(f"You are now chatting with **{person_name}**!") elif mode == "Study with a Tutor": topic = st.sidebar.selectbox("Choose a Study Topic", ["Mathematics", "History", "Physics"]) st.write(f"You are now studying **{topic}**!") # Chat input if "messages" not in st.session_state: st.session_state.messages = [] for msg in st.session_state.messages: st.chat_message(msg["role"]).write(msg["content"]) user_input = st.chat_input("Type your message here...") if user_input and mode == "Chat with Historical Figures" and person_name: st.session_state.messages.append({"role": "user", "content": user_input}) st.chat_message("user").write(user_input) response = chat_with_ai(person_name, user_input) st.session_state.messages.append({"role": "assistant", "content": response}) st.chat_message("assistant").write(response) # Deployment instructions st.sidebar.subheader("Deployment Instructions") st.sidebar.markdown("1. Add the API key as a secret in Hugging Face Spaces.") st.sidebar.markdown("2. Run `streamlit run app.py` locally or deploy on Hugging Face Spaces.")