Spaces:
Sleeping
Sleeping
import os | |
import re | |
import streamlit as st | |
from huggingface_hub import InferenceClient | |
from dotenv import load_dotenv | |
# Load environment variables from .env file | |
load_dotenv() | |
# Set Streamlit page configuration | |
st.set_page_config(page_title="🎓 Education Fellow Chatbot", layout="wide") | |
st.title("🎓 Education Fellow Chatbot") | |
# Initialize session state for chat history | |
if "history" not in st.session_state: | |
st.session_state.history = [] # stores tuples of (sender, message) | |
# Initialize the Hugging Face Inference Client | |
try: | |
hf_token = os.environ["HUGGINGFACEHUB_API_TOKEN"] | |
client = InferenceClient( | |
model="deepseek-ai/DeepSeek-R1", | |
token=hf_token | |
) | |
except KeyError: | |
st.error("❌ HUGGINGFACEHUB_API_TOKEN is not set in environment variables.") | |
st.stop() | |
# Function to structure chat history as messages for the API | |
def build_messages(): | |
return [ | |
{"role": "user" if sender == "You" else "assistant", "content": message} | |
for sender, message in st.session_state.history | |
] | |
# Function to remove <think> tags from the model response | |
def clean_think_tags(text: str) -> str: | |
return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip() | |
# Display previous chat messages | |
for sender, message in st.session_state.history: | |
with st.chat_message("user" if sender == "You" else "assistant"): | |
st.write(message) | |
# Chat input box | |
user_input = st.chat_input("Ask me anything related to education, classrooms, or pedagogy…") | |
# If there's new input from the user | |
if user_input: | |
st.session_state.history.append(("You", user_input)) | |
with st.chat_message("user"): | |
st.write(user_input) | |
with st.chat_message("assistant"): | |
placeholder = st.empty() | |
placeholder.write("⏳ Thinking...") | |
try: | |
response = client.chat.completions.create( | |
model="deepseek-ai/DeepSeek-R1", | |
messages=build_messages() | |
) | |
raw_output = response.choices[0].message["content"] | |
reply = clean_think_tags(raw_output) | |
except Exception as e: | |
reply = f"❌ API Error: {e}" | |
placeholder.write(reply) | |
st.session_state.history.append(("Bot", reply)) | |