saikumar27 commited on
Commit
fbf97c0
Β·
verified Β·
1 Parent(s): 487a87f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -54
app.py CHANGED
@@ -1,88 +1,78 @@
1
-
2
  import streamlit as st
3
- from langchain import HuggingFacePipeline, LLMChain
 
4
  from langchain.memory import ConversationBufferMemory
5
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
6
  import os
 
7
 
8
- # 🌟 Step 1: Configure API Key
9
- os.environ["HUGGINGFACE_API_KEY"] = st.secrets["HUGGINGFACE_API_KEY"]
10
-
11
- # 🌟 Step 2: Load Hugging Face Model
12
- @st.cache_resource
13
- def load_model():
14
- model_id = "tiiuae/falcon-7b-instruct" # You can change the model if needed
15
- tokenizer = AutoTokenizer.from_pretrained(model_id)
16
- model = AutoModelForCausalLM.from_pretrained(model_id)
17
 
18
- generator = pipeline(
19
- task="text-generation",
20
- model=model,
21
- tokenizer=tokenizer,
22
- max_new_tokens=500 # Limit the response length
23
- )
24
- return generator
25
 
26
- generator = load_model()
 
27
 
28
- # 🌟 Step 3: Set Up LangChain with Memory
29
  memory = ConversationBufferMemory()
30
 
31
- llm = HuggingFacePipeline(pipeline=generator)
 
 
 
 
 
 
32
 
33
- # Restrict the AI to Data Science Questions
34
- system_prompt = """
35
- You are a highly knowledgeable Data Science tutor.
36
- You must answer only data science-related questions.
37
- If the user asks something unrelated, politely inform them that you are designed to handle data science queries only.
38
  """
39
 
40
- chain = LLMChain(
41
- llm=llm,
 
42
  memory=memory,
43
- prompt=system_prompt
44
  )
45
 
46
- # 🌟 Step 4: Build Streamlit UI
47
- st.set_page_config(page_title="πŸ€– Data Science Tutor", layout="wide")
48
-
49
- # Title and description
50
- st.title("πŸ€– Data Science Tutor")
51
- st.write("Ask me anything about Data Science!")
52
 
53
- # Initialize session state for messages
54
  if "messages" not in st.session_state:
55
  st.session_state.messages = []
56
 
57
- # Display chat history
58
  for message in st.session_state.messages:
59
  with st.chat_message(message["role"]):
60
  st.markdown(message["content"])
61
 
62
- # 🌟 Step 5: Handle User Input
63
- user_input = st.chat_input("Ask your data science question here...")
64
 
65
  if user_input:
66
- # Add user input to session state
67
  st.session_state.messages.append({"role": "user", "content": user_input})
 
 
68
 
69
- # Create prompt for the model
70
- prompt = f"""
71
- You are a Data Science Tutor.
72
- Answer the following question ONLY if it is related to data science:
73
- {user_input}
74
- """
75
 
76
- # Generate AI response
77
  with st.chat_message("assistant"):
78
- with st.spinner("Thinking..."):
79
- response = chain.run(prompt)
80
- st.markdown(response)
81
 
82
- # Store AI response in session state
83
  st.session_state.messages.append({"role": "assistant", "content": response})
84
 
85
- # 🌟 Step 6: Option to Clear Chat
86
- if st.button("Clear Chat"):
87
  st.session_state.messages = []
 
88
  st.experimental_rerun()
 
 
1
  import streamlit as st
2
+ from langchain_google_genai import ChatGoogleGenerativeAI
3
+ from langchain.chains import ConversationChain
4
  from langchain.memory import ConversationBufferMemory
5
+ from langchain.prompts import PromptTemplate
6
  import os
7
+ from dotenv import load_dotenv
8
 
9
+ # βœ… Load API Key from Environment Variables
10
+ load_dotenv()
11
+ api_key = os.getenv("GOOGLE_API_KEY")
 
 
 
 
 
 
12
 
13
+ if not api_key:
14
+ st.error("🚨 API key missing! Add your GOOGLE_API_KEY to the environment variables.")
15
+ st.stop()
 
 
 
 
16
 
17
+ # βœ… Configure Gemini Model
18
+ model = ChatGoogleGenerativeAI(model="gemini-1.5-pro", api_key=api_key)
19
 
20
+ # βœ… Add Memory to Make It Context-Aware
21
  memory = ConversationBufferMemory()
22
 
23
+ # βœ… Define Prompt for Data Science Focus
24
+ prompt_template = """
25
+ You are an AI Data Science tutor.
26
+ - Your task is to help the user with data science-related queries ONLY.
27
+ - If the question is unrelated to data science, politely refuse to answer.
28
+ - Provide clear, detailed, and accurate explanations with examples where applicable.
29
+ - Avoid overly technical language unless necessary.
30
 
31
+ User: {input}
32
+ AI:
 
 
 
33
  """
34
 
35
+ # βœ… Create Conversation Chain
36
+ conversation = ConversationChain(
37
+ llm=model,
38
  memory=memory,
39
+ prompt=PromptTemplate(template=prompt_template, input_variables=["input"])
40
  )
41
 
42
+ # βœ… Streamlit UI
43
+ st.set_page_config(page_title="AI Data Science Tutor", layout="wide")
44
+ st.title("🧠 Conversational AI Data Science Tutor")
 
 
 
45
 
46
+ # Display chat history
47
  if "messages" not in st.session_state:
48
  st.session_state.messages = []
49
 
50
+ # Display previous messages
51
  for message in st.session_state.messages:
52
  with st.chat_message(message["role"]):
53
  st.markdown(message["content"])
54
 
55
+ # User Input
56
+ user_input = st.chat_input("Ask me a data science question...")
57
 
58
  if user_input:
59
+ # Display user message
60
  st.session_state.messages.append({"role": "user", "content": user_input})
61
+ with st.chat_message("user"):
62
+ st.markdown(user_input)
63
 
64
+ # Generate response
65
+ response = conversation.predict(input=user_input)
 
 
 
 
66
 
67
+ # Display AI response
68
  with st.chat_message("assistant"):
69
+ st.markdown(response)
 
 
70
 
71
+ # Store AI message
72
  st.session_state.messages.append({"role": "assistant", "content": response})
73
 
74
+ # βœ… Reset Chat Button
75
+ if st.button("Reset Chat"):
76
  st.session_state.messages = []
77
+ memory.clear()
78
  st.experimental_rerun()