File size: 2,257 Bytes
4dc4da2
 
 
 
 
 
 
 
 
 
230b131
 
4dc4da2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230b131
4dc4da2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230b131
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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))