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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -23
app.py CHANGED
@@ -3,30 +3,93 @@ 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
- st.write('hello welecome to data science tutor')
12
- # Database file name
13
- DB_PATH = "database.db"
14
-
15
- # Function to create a database and table if not exists
16
- def create_database():
17
- if not os.path.exists(DB_PATH): # Check if database exists
18
- conn = sqlite3.connect(DB_PATH)
19
- cursor = conn.cursor()
20
-
21
- # Create a sample table
22
- cursor.execute("""
23
- CREATE TABLE IF NOT EXISTS users (
24
- id INTEGER PRIMARY KEY AUTOINCREMENT,
25
- name TEXT NOT NULL,
26
- age INTEGER NOT NULL
27
- )
28
- """)
29
- conn.commit()
30
- conn.close()
31
- st.success("Database and table created successfully!")
32
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (
23
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
24
+ session_id TEXT,
25
+ role TEXT,
26
+ content TEXT
27
+ )
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
46
+ if "session_id" not in st.session_state:
47
+ st.session_state.session_id = str(uuid.uuid4())
48
+
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
63
+ out_parser = StrOutputParser()
64
+
65
+ # Create a chain
66
+ chain = chat_prompt | llm | out_parser
67
+
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)