Phaneendrabayi commited on
Commit
c7ffe8b
Β·
verified Β·
1 Parent(s): fea17ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -55
app.py CHANGED
@@ -1,11 +1,18 @@
1
  import streamlit as st
2
- import google.generativeai as genai
3
- import sqlite3
4
  import uuid
5
- from langchain_community.chat_message_histories import SQLChatMessageHistory
6
  from langchain.schema import SystemMessage, HumanMessage, AIMessage
 
 
 
 
 
 
 
 
 
7
 
8
- # Initialize Database at the Very Beginning
9
  def init_db():
10
  conn = sqlite3.connect("chat_history.db")
11
  c = conn.cursor()
@@ -20,85 +27,78 @@ def init_db():
20
  conn.commit()
21
  conn.close()
22
 
23
- init_db() # Ensure DB is created before any operations
24
-
25
- # Configure API Key
26
- genai.configure(api_key="AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo")
27
-
28
- # System Prompt
29
- sys_prompt = """You are a helpful data science tutor. You can only resolve data science-related queries. \
30
- If someone asks unrelated queries, politely ask them to stay on topic."""
31
-
32
- # Load Model
33
- model = genai.GenerativeModel(model_name='gemini-1.5-flash', system_instruction=sys_prompt)
34
-
35
- # Save Chat History
36
- def save_chat(user_id, message, response):
37
  conn = sqlite3.connect("chat_history.db")
38
  c = conn.cursor()
39
- c.execute("INSERT INTO chat_history (user_id, message, response) VALUES (?, ?, ?)", (user_id, message, response))
40
- conn.commit()
41
  conn.close()
 
42
 
43
- # Retrieve Chat History
44
- def get_chat_history(user_id):
45
  conn = sqlite3.connect("chat_history.db")
46
  c = conn.cursor()
47
- c.execute("SELECT id, message, response FROM chat_history WHERE user_id = ?", (user_id,))
48
- data = c.fetchall()
49
  conn.close()
50
- return data
51
 
52
- # Delete Selected Chat
53
- def delete_chat(chat_id):
54
  conn = sqlite3.connect("chat_history.db")
55
  c = conn.cursor()
56
- c.execute("DELETE FROM chat_history WHERE id = ?", (chat_id,))
57
  conn.commit()
58
  conn.close()
59
 
60
  # Streamlit UI
61
- st.set_page_config(page_title="Data Science Tutor AI", layout="wide")
62
- st.title("πŸ€– Data Science Tutor (AI)")
63
  st.sidebar.header("Chat History")
64
 
65
  # User Session
66
  if "user_id" not in st.session_state:
67
  st.session_state.user_id = str(uuid.uuid4())
68
 
69
- # βœ… Fix: Initialize chat messages list in session state
70
- if "messages" not in st.session_state:
71
- st.session_state.messages = []
72
 
73
  # Layout with Chat Interface
74
  col1, col2 = st.columns([3, 1])
75
 
76
  with col1:
77
- st.write("Ask me any data science-related question!")
78
- user_prompt = st.text_input("Enter your query:", key="user_input")
79
-
80
- if st.button("πŸš€ Send", key="send_button") and user_prompt:
81
- response = model.generate_content(user_prompt).text
82
- save_chat(st.session_state.user_id, user_prompt, response)
83
- st.session_state.messages.append((user_prompt, response))
84
 
85
- # Display Chat History in Chat Format
86
- chat_history = get_chat_history(st.session_state.user_id)
87
  st.subheader("Chat")
88
  chat_container = st.container()
89
-
90
- for chat in chat_history:
91
- chat_id, message, response = chat
92
  with chat_container:
93
- st.markdown(f"<div style='border-radius: 10px; padding: 10px; background-color: #DCF8C6; margin: 5px;'><b>You:</b> {message}</div>", unsafe_allow_html=True)
94
- st.markdown(f"<div style='border-radius: 10px; padding: 10px; background-color: #ECECEC; margin: 5px;'><b>AI:</b> {response}</div>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
95
 
96
  with col2:
97
- # Display Chat History in Sidebar with Delete Option
98
- chat_history = get_chat_history(st.session_state.user_id)
99
- for chat in chat_history:
100
- chat_id, message, _ = chat
101
- with st.sidebar.expander(message):
102
- if st.button("πŸ—‘ Delete", key=f"delete_{chat_id}"):
103
- delete_chat(chat_id)
104
- st.experimental_rerun()
 
1
  import streamlit as st
 
 
2
  import uuid
3
+ from langchain_google_genai import ChatGoogleGenerativeAI
4
  from langchain.schema import SystemMessage, HumanMessage, AIMessage
5
+ from langchain.memory import ConversationBufferMemory
6
+ from langchain.memory.chat_message_histories import SQLChatMessageHistory
7
+ from langchain_core.output_parsers import StrOutputParser
8
+ import sqlite3
9
+
10
+ # Configure Gemini API
11
+ GEMINI_API_KEY = "AIzaSyBuhWQHGfMQewIY_gdnmbzzYoori6faeUo"
12
+ model = ChatGoogleGenerativeAI(model="gemini-2.0-pro-exp", google_api_key=GEMINI_API_KEY)
13
+ output_parser = StrOutputParser()
14
 
15
+ # Initialize Database
16
  def init_db():
17
  conn = sqlite3.connect("chat_history.db")
18
  c = conn.cursor()
 
27
  conn.commit()
28
  conn.close()
29
 
30
+ # Retrieve past chat history
31
+ def get_chat_history(user_id):
 
 
 
 
 
 
 
 
 
 
 
 
32
  conn = sqlite3.connect("chat_history.db")
33
  c = conn.cursor()
34
+ c.execute("SELECT message, response FROM chat_history WHERE user_id = ?", (user_id,))
35
+ data = c.fetchall()
36
  conn.close()
37
+ return data
38
 
39
+ # Save chat history
40
+ def save_chat(user_id, message, response):
41
  conn = sqlite3.connect("chat_history.db")
42
  c = conn.cursor()
43
+ c.execute("INSERT INTO chat_history (user_id, message, response) VALUES (?, ?, ?)", (user_id, message, response))
44
+ conn.commit()
45
  conn.close()
 
46
 
47
+ # Delete chat history
48
+ def delete_chat_history(user_id):
49
  conn = sqlite3.connect("chat_history.db")
50
  c = conn.cursor()
51
+ c.execute("DELETE FROM chat_history WHERE user_id = ?", (user_id,))
52
  conn.commit()
53
  conn.close()
54
 
55
  # Streamlit UI
56
+ st.set_page_config(page_title="AI Chatbot", layout="wide")
57
+ st.title("πŸ€– AI Chatbot")
58
  st.sidebar.header("Chat History")
59
 
60
  # User Session
61
  if "user_id" not in st.session_state:
62
  st.session_state.user_id = str(uuid.uuid4())
63
 
64
+ # Retrieve chat history
65
+ chat_history = get_chat_history(st.session_state.user_id)
 
66
 
67
  # Layout with Chat Interface
68
  col1, col2 = st.columns([3, 1])
69
 
70
  with col1:
71
+ st.write("Ask me anything!")
72
+ user_input = st.text_input("Enter your query:", key="user_input")
73
+ if st.button("πŸš€ Send") and user_input:
74
+ response = model.invoke([SystemMessage(content="You are a helpful AI agent."), HumanMessage(content=user_input)]).content.strip()
75
+ parsed_response = output_parser.parse(response)
76
+ save_chat(st.session_state.user_id, user_input, parsed_response)
77
+ chat_history.append((user_input, parsed_response))
78
 
79
+ # Display Chat History in WhatsApp-style Chat Format
 
80
  st.subheader("Chat")
81
  chat_container = st.container()
82
+ for message, response in chat_history:
 
 
83
  with chat_container:
84
+ st.markdown(f"""
85
+ <div style='display: flex; justify-content: flex-end; margin: 5px;'>
86
+ <div style='border-radius: 15px; padding: 10px; background-color: #DCF8C6; max-width: 70%;'>
87
+ <b>You:</b> {message}
88
+ </div>
89
+ </div>
90
+ <div style='display: flex; justify-content: flex-start; margin: 5px;'>
91
+ <div style='border-radius: 15px; padding: 10px; background-color: #EAEAEA; max-width: 70%;'>
92
+ <b>AI:</b> {response}
93
+ </div>
94
+ </div>
95
+ """, unsafe_allow_html=True)
96
 
97
  with col2:
98
+ # Option to Clear Chat History
99
+ if st.sidebar.button("πŸ—‘ Clear Chat History"):
100
+ delete_chat_history(st.session_state.user_id)
101
+ st.experimental_rerun()
102
+
103
+ # Initialize Database
104
+ init_db()