Mpavan45 commited on
Commit
e507109
·
verified ·
1 Parent(s): c4ba536

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -19
app.py CHANGED
@@ -1,22 +1,20 @@
1
  import streamlit as st
2
  import sqlite3
3
  import uuid
4
- import langchain
5
  from langchain_google_genai import GoogleGenerativeAI
6
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
7
  from langchain_core.output_parsers import StrOutputParser
8
  from langchain_community.chat_message_histories import SQLChatMessageHistory
9
  from langchain_core.runnables.history import RunnableWithMessageHistory
10
 
11
- # Load API key from file
12
- # ✅ Access Hugging Face Secret API Key
13
  GOOGLE_API_KEY = st.secrets.get("GOOGLE_API_KEY")
14
 
15
- # Set up the Gemini 2.0 Flash model
16
  llm = GoogleGenerativeAI(api_key=GOOGLE_API_KEY, model="gemini-1.5-pro")
17
 
18
  # Initialize SQLite database for chat history
19
- conn = sqlite3.connect("chat_history.db")
20
  cursor = conn.cursor()
21
  cursor.execute("""
22
  CREATE TABLE IF NOT EXISTS chat (
@@ -28,18 +26,21 @@ CREATE TABLE IF NOT EXISTS chat (
28
  """)
29
  conn.commit()
30
 
 
31
  def save_message(session_id, role, content):
32
  cursor.execute("INSERT INTO chat (session_id, role, content) VALUES (?, ?, ?)", (session_id, role, content))
33
  conn.commit()
34
 
 
35
  def load_chat_history(session_id):
36
  cursor.execute("SELECT role, content FROM chat WHERE session_id = ?", (session_id,))
37
  return cursor.fetchall()
38
 
 
39
  def chat_history(session_id):
40
  return SQLChatMessageHistory(
41
  session_id=session_id,
42
- connection='sqlite:///chat_history.db'
43
  )
44
 
45
  # Generate unique session ID for each user
@@ -49,14 +50,16 @@ if "session_id" not in st.session_state:
49
  session_id = st.session_state.session_id
50
  chat_history_instance = chat_history(session_id)
51
 
52
- # Define Chat Prompt Template
53
  chat_prompt = ChatPromptTemplate(
54
- messages=[('system', ''''You are an AI assistant.You are a Data Science tutor. You provide answers only about Data Science.Answer every question as deeply as possible.
55
- If asked anything outside this topic, do not respond and instead prompt the user to ask a Data Science-related question.
56
- Only provide responses related to Data Science.
57
- '''),
58
- MessagesPlaceholder(variable_name="history", optional=True),
59
- ('human', '{prompt}')]
 
 
60
  )
61
 
62
  # Define output parser
@@ -68,28 +71,36 @@ chain = chat_prompt | llm | out_parser
68
  # Define Runnable with message history
69
  chat = RunnableWithMessageHistory(
70
  chain,
71
- chat_history,
72
- input_messages_key='prompt',
73
- history_messages_key='history'
74
  )
75
 
76
  # Streamlit UI
77
  st.title("Conversational AI Data Science Tutor")
78
  st.write("Ask me anything about Data Science!")
79
 
80
- # Load chat history from database
81
- st.session_state.messages = load_chat_history(session_id)
82
 
 
83
  for role, content in st.session_state.messages:
84
  with st.chat_message(role):
85
  st.markdown(content)
86
 
 
87
  user_input = st.text_input("You:", "", key="user_input")
 
88
  if user_input:
89
  save_message(session_id, "user", user_input)
90
  st.session_state.messages.append(("user", user_input))
 
 
91
  config = {'configurable': {'session_id': session_id}}
92
  response = chat.invoke({'prompt': user_input}, config)
 
93
  save_message(session_id, "assistant", response)
94
  st.session_state.messages.append(("assistant", response))
95
- st.chat_message("assistant").markdown(response)
 
 
 
1
  import streamlit as st
2
  import sqlite3
3
  import uuid
 
4
  from langchain_google_genai import GoogleGenerativeAI
5
  from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
6
  from langchain_core.output_parsers import StrOutputParser
7
  from langchain_community.chat_message_histories import SQLChatMessageHistory
8
  from langchain_core.runnables.history import RunnableWithMessageHistory
9
 
10
+ # Load API key from secrets
 
11
  GOOGLE_API_KEY = st.secrets.get("GOOGLE_API_KEY")
12
 
13
+ # Set up the Gemini 1.5 Pro model
14
  llm = GoogleGenerativeAI(api_key=GOOGLE_API_KEY, model="gemini-1.5-pro")
15
 
16
  # Initialize SQLite database for chat history
17
+ conn = sqlite3.connect("chat_history.db", check_same_thread=False)
18
  cursor = conn.cursor()
19
  cursor.execute("""
20
  CREATE TABLE IF NOT EXISTS chat (
 
26
  """)
27
  conn.commit()
28
 
29
+ # Function to save messages
30
  def save_message(session_id, role, content):
31
  cursor.execute("INSERT INTO chat (session_id, role, content) VALUES (?, ?, ?)", (session_id, role, content))
32
  conn.commit()
33
 
34
+ # Function to load chat history
35
  def load_chat_history(session_id):
36
  cursor.execute("SELECT role, content FROM chat WHERE session_id = ?", (session_id,))
37
  return cursor.fetchall()
38
 
39
+ # Chat history instance
40
  def chat_history(session_id):
41
  return SQLChatMessageHistory(
42
  session_id=session_id,
43
+ connection=conn # FIXED: Pass direct SQLite connection
44
  )
45
 
46
  # Generate unique session ID for each user
 
50
  session_id = st.session_state.session_id
51
  chat_history_instance = chat_history(session_id)
52
 
53
+ # Define Chat Prompt Template (FIXED)
54
  chat_prompt = ChatPromptTemplate(
55
+ messages=[
56
+ ('system', """You are an AI assistant specialized in Data Science tutoring.
57
+ You will only answer questions related to Data Science.
58
+ If asked anything outside this topic, politely decline and request a Data Science-related question.
59
+ """),
60
+ MessagesPlaceholder(variable_name="history", optional=True),
61
+ ('human', '{prompt}')
62
+ ]
63
  )
64
 
65
  # Define output parser
 
71
  # Define Runnable with message history
72
  chat = RunnableWithMessageHistory(
73
  chain,
74
+ lambda session: SQLChatMessageHistory(session, conn), # FIXED: Pass connection correctly
75
+ input_messages_key="prompt",
76
+ history_messages_key="history"
77
  )
78
 
79
  # Streamlit UI
80
  st.title("Conversational AI Data Science Tutor")
81
  st.write("Ask me anything about Data Science!")
82
 
83
+ # Load chat history
84
+ st.session_state.setdefault("messages", load_chat_history(session_id))
85
 
86
+ # Display chat history
87
  for role, content in st.session_state.messages:
88
  with st.chat_message(role):
89
  st.markdown(content)
90
 
91
+ # User input
92
  user_input = st.text_input("You:", "", key="user_input")
93
+
94
  if user_input:
95
  save_message(session_id, "user", user_input)
96
  st.session_state.messages.append(("user", user_input))
97
+
98
+ # Invoke the AI model
99
  config = {'configurable': {'session_id': session_id}}
100
  response = chat.invoke({'prompt': user_input}, config)
101
+
102
  save_message(session_id, "assistant", response)
103
  st.session_state.messages.append(("assistant", response))
104
+
105
+ with st.chat_message("assistant"):
106
+ st.markdown(response)