chatbot / app.py
devfire's picture
Update app.py
c2b781b verified
raw
history blame
2.88 kB
import os
import streamlit as st
from groq import Groq
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
# Set up the Groq API Key
GROQ_API_KEY = "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"
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
# Initialize the Groq client
client = Groq(api_key=GROQ_API_KEY)
# Initialize Hugging Face DeepSeek R1 model
pipe = pipeline("text-generation", model="deepseek-ai/DeepSeek-R1", trust_remote_code=True)
def generate_response_hf(user_message):
response = pipe(user_message, max_length=200, do_sample=True)
return response[0]['generated_text']
# Streamlit user interface setup
st.set_page_config(page_title="AI Study Assistant", page_icon="πŸ€–", layout="wide")
st.title("πŸ“š Subject-specific AI Chatbot")
st.write("Hello! I'm your AI Study Assistant. You can ask me any questions related to your subjects, and I'll try to help.")
# Add sidebar with settings
st.sidebar.header("βš™οΈ Settings")
st.sidebar.write("Customize your chatbot experience!")
chat_model = st.sidebar.radio("Choose AI Model:", ["Groq API", "DeepSeek R1 (Hugging Face)"])
# Initialize session state for maintaining conversation
if 'conversation_history' not in st.session_state:
st.session_state.conversation_history = []
# Define a list of subjects for which the chatbot will answer
subjects = ["Chemistry", "Computer", "English", "Islamiat", "Mathematics", "Physics", "Urdu"]
def generate_chatbot_response(user_message):
related_subject = next((subject for subject in subjects if subject.lower() in user_message.lower()), None)
if "kisne banaya" in user_message.lower() or "who created you" in user_message.lower():
return "I was created by Abdul Basit 😊"
prompt = f"You are a helpful AI chatbot for studying {related_subject if related_subject else 'general knowledge'}. The user is asking: {user_message}. Provide a detailed, helpful response."
if chat_model == "Groq API":
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="deepseek-chat"
)
return chat_completion.choices[0].message.content
else:
return generate_response_hf(prompt)
# User input for conversation
st.markdown("### πŸ’¬ Chat with me")
user_input = st.chat_input("Ask me a subject-related question:")
if user_input:
chatbot_response = generate_chatbot_response(user_input)
st.session_state.conversation_history.append(("User: " + user_input, "Chatbot: " + chatbot_response))
# Display chat history
st.markdown("---")
st.markdown("### πŸ—¨οΈ Chat History")
for question, answer in st.session_state.conversation_history:
st.write(f"<div class='chat-bubble'><b>{question}</b></div>", unsafe_allow_html=True)
st.write(f"<div class='chat-bubble'>{answer}</div>", unsafe_allow_html=True)