shukdevdatta123 commited on
Commit
47402a5
Β·
verified Β·
1 Parent(s): c902f8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -141
app.py CHANGED
@@ -1,141 +1,142 @@
1
- import os
2
- import pandas as pd
3
- import streamlit as st
4
- from llama_index.experimental.query_engine import PandasQueryEngine
5
- from prompts import new_prompt, instruction_str, context
6
- from note_engine import note_engine
7
- from llama_index.core.tools import QueryEngineTool, ToolMetadata
8
- from llama_index.core.agent import ReActAgent
9
- from llama_index.llms.openai import OpenAI
10
- from data_summary import data_summary_tool
11
- from pdf import bangladesh_engine
12
- from dotenv import load_dotenv
13
-
14
- # Load environment variables
15
- load_dotenv()
16
-
17
- # File paths
18
- conversation_file = os.path.join("data", "conversation.txt")
19
- summary_file = os.path.join("data", "data_summary.txt")
20
- population_path = os.path.join("data", "Population.csv")
21
- population_df = pd.read_csv(population_path)
22
-
23
- # Set up the Streamlit app
24
- st.title("🌎 Population and Bangladesh Data Assistant")
25
-
26
- # Sidebar for OpenAI API key
27
- api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
28
- if api_key:
29
- os.environ["OPENAI_API_KEY"] = api_key
30
-
31
- # Initialize query engines
32
- population_query_engine = PandasQueryEngine(
33
- df=population_df, verbose=True, instruction_str=instruction_str
34
- )
35
-
36
- population_query_engine.update_prompts({"pandas_prompt": new_prompt})
37
-
38
- tools = [
39
- QueryEngineTool(
40
- query_engine=population_query_engine,
41
- metadata=ToolMetadata(
42
- name="population_data",
43
- description="Provides information about world population and demographics",
44
- ),
45
- ),
46
- QueryEngineTool(
47
- query_engine=bangladesh_engine,
48
- metadata=ToolMetadata(
49
- name="bangladesh_data",
50
- description="Provides detailed information about Bangladesh",
51
- ),
52
- ),
53
- ]
54
-
55
- llm = OpenAI(model="gpt-3.5-turbo")
56
- agent = ReActAgent.from_tools(tools, llm=llm, verbose=True, context=context)
57
-
58
- # Sidebar options
59
- st.sidebar.header("Options")
60
- option = st.sidebar.selectbox("Choose an action:", [
61
- "Ask a Question",
62
- "View Previous Conversations",
63
- "View Data Summary",
64
- "Save a Note"
65
- ])
66
-
67
- # Conversation management
68
- conversation_active = st.session_state.get('conversation_active', False)
69
-
70
- if option == "Ask a Question":
71
- if not conversation_active:
72
- st.session_state.conversation_active = True
73
- st.session_state.conversation_history = []
74
-
75
- prompt = st.text_area("Enter your query:", key="user_input")
76
-
77
- if st.button("Submit"):
78
- if prompt:
79
- result = agent.query(prompt)
80
- response_text = result.response # Extract just the response text
81
- st.write("Response:", response_text) # Show only the response text
82
-
83
- # Save the conversation with a timestamp
84
- timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
85
- st.session_state.conversation_history.append((timestamp, prompt, response_text))
86
- else:
87
- st.error("Please enter a query.")
88
-
89
- if st.button("Save this Conversation"):
90
- # Save entire conversation history to the file
91
- with open(conversation_file, "a") as file:
92
- for timestamp, user_prompt, bot_response in st.session_state.conversation_history:
93
- file.write(f"Timestamp: {timestamp}\n")
94
- file.write(f"Prompt: {user_prompt}\n")
95
- file.write(f"Response: {bot_response}\n")
96
- file.write("=" * 40 + "\n")
97
- st.success("Conversation saved.")
98
-
99
- if st.button("End Conversation"):
100
- st.session_state.conversation_active = False
101
- st.success("Conversation ended.")
102
-
103
- # View previous conversations
104
- elif option == "View Previous Conversations":
105
- if os.path.exists(conversation_file):
106
- with open(conversation_file, "r") as file:
107
- st.text_area("Previous Conversations", file.read(), height=300)
108
- else:
109
- st.warning("No previous conversations found.")
110
-
111
- # View data summary
112
- elif option == "View Data Summary":
113
- if os.path.exists(summary_file):
114
- with open(summary_file, "r") as file:
115
- st.text_area("Data Summary", file.read(), height=300)
116
- else:
117
- st.warning("No data summary found.")
118
-
119
- # Save a note
120
- elif option == "Save a Note":
121
- note = st.text_input("Enter a note to save:")
122
- if st.button("Save Note"):
123
- if note:
124
- # Append note to the conversation file with a timestamp
125
- timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
126
- with open(conversation_file, "a") as file:
127
- file.write(f"Timestamp: {timestamp} (Note)\n")
128
- file.write(f"Note: {note}\n")
129
- file.write("=" * 40 + "\n") # Separator for readability
130
- st.success("Note saved.")
131
- else:
132
- st.error("Please enter a note.")
133
-
134
- # Instructions
135
- st.sidebar.subheader("Instructions")
136
- st.sidebar.write(
137
- "1. Enter your OpenAI API Key in the sidebar.\n"
138
- "2. Use the sidebar to choose an action: ask a question, view previous conversations, view the data summary, or save a note.\n"
139
- "3. If you ask a question and click save, the conversation will be saved. If you ask multiple questions and then press save, it will save the whole conversation.\n"
140
- "4. The End Conversation button will simply end the conversation without saving anything.\n"
141
- )
 
 
1
+ import os
2
+ import pandas as pd
3
+ import streamlit as st
4
+ from llama_index.experimental.query_engine import PandasQueryEngine
5
+ from prompts import new_prompt, instruction_str, context
6
+ from note_engine import note_engine
7
+ from llama_index.core.tools import QueryEngineTool, ToolMetadata
8
+ from llama_index.core.agent import ReActAgent
9
+ from llama_index.llms.openai import OpenAI
10
+ from langchain_core.language_models.cache import BaseCache
11
+ from data_summary import data_summary_tool
12
+ from pdf import bangladesh_engine
13
+ from dotenv import load_dotenv
14
+
15
+ # Load environment variables
16
+ load_dotenv()
17
+
18
+ # File paths
19
+ conversation_file = os.path.join("data", "conversation.txt")
20
+ summary_file = os.path.join("data", "data_summary.txt")
21
+ population_path = os.path.join("data", "Population.csv")
22
+ population_df = pd.read_csv(population_path)
23
+
24
+ # Set up the Streamlit app
25
+ st.title("🌎 Population and Bangladesh Data Assistant")
26
+
27
+ # Sidebar for OpenAI API key
28
+ api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
29
+ if api_key:
30
+ os.environ["OPENAI_API_KEY"] = api_key
31
+
32
+ # Initialize query engines
33
+ population_query_engine = PandasQueryEngine(
34
+ df=population_df, verbose=True, instruction_str=instruction_str
35
+ )
36
+
37
+ population_query_engine.update_prompts({"pandas_prompt": new_prompt})
38
+
39
+ tools = [
40
+ QueryEngineTool(
41
+ query_engine=population_query_engine,
42
+ metadata=ToolMetadata(
43
+ name="population_data",
44
+ description="Provides information about world population and demographics",
45
+ ),
46
+ ),
47
+ QueryEngineTool(
48
+ query_engine=bangladesh_engine,
49
+ metadata=ToolMetadata(
50
+ name="bangladesh_data",
51
+ description="Provides detailed information about Bangladesh",
52
+ ),
53
+ ),
54
+ ]
55
+
56
+ llm = OpenAI(model="gpt-3.5-turbo")
57
+ agent = ReActAgent.from_tools(tools, llm=llm, verbose=True, context=context)
58
+
59
+ # Sidebar options
60
+ st.sidebar.header("Options")
61
+ option = st.sidebar.selectbox("Choose an action:", [
62
+ "Ask a Question",
63
+ "View Previous Conversations",
64
+ "View Data Summary",
65
+ "Save a Note"
66
+ ])
67
+
68
+ # Conversation management
69
+ conversation_active = st.session_state.get('conversation_active', False)
70
+
71
+ if option == "Ask a Question":
72
+ if not conversation_active:
73
+ st.session_state.conversation_active = True
74
+ st.session_state.conversation_history = []
75
+
76
+ prompt = st.text_area("Enter your query:", key="user_input")
77
+
78
+ if st.button("Submit"):
79
+ if prompt:
80
+ result = agent.query(prompt)
81
+ response_text = result.response # Extract just the response text
82
+ st.write("Response:", response_text) # Show only the response text
83
+
84
+ # Save the conversation with a timestamp
85
+ timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
86
+ st.session_state.conversation_history.append((timestamp, prompt, response_text))
87
+ else:
88
+ st.error("Please enter a query.")
89
+
90
+ if st.button("Save this Conversation"):
91
+ # Save entire conversation history to the file
92
+ with open(conversation_file, "a") as file:
93
+ for timestamp, user_prompt, bot_response in st.session_state.conversation_history:
94
+ file.write(f"Timestamp: {timestamp}\n")
95
+ file.write(f"Prompt: {user_prompt}\n")
96
+ file.write(f"Response: {bot_response}\n")
97
+ file.write("=" * 40 + "\n")
98
+ st.success("Conversation saved.")
99
+
100
+ if st.button("End Conversation"):
101
+ st.session_state.conversation_active = False
102
+ st.success("Conversation ended.")
103
+
104
+ # View previous conversations
105
+ elif option == "View Previous Conversations":
106
+ if os.path.exists(conversation_file):
107
+ with open(conversation_file, "r") as file:
108
+ st.text_area("Previous Conversations", file.read(), height=300)
109
+ else:
110
+ st.warning("No previous conversations found.")
111
+
112
+ # View data summary
113
+ elif option == "View Data Summary":
114
+ if os.path.exists(summary_file):
115
+ with open(summary_file, "r") as file:
116
+ st.text_area("Data Summary", file.read(), height=300)
117
+ else:
118
+ st.warning("No data summary found.")
119
+
120
+ # Save a note
121
+ elif option == "Save a Note":
122
+ note = st.text_input("Enter a note to save:")
123
+ if st.button("Save Note"):
124
+ if note:
125
+ # Append note to the conversation file with a timestamp
126
+ timestamp = pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S")
127
+ with open(conversation_file, "a") as file:
128
+ file.write(f"Timestamp: {timestamp} (Note)\n")
129
+ file.write(f"Note: {note}\n")
130
+ file.write("=" * 40 + "\n") # Separator for readability
131
+ st.success("Note saved.")
132
+ else:
133
+ st.error("Please enter a note.")
134
+
135
+ # Instructions
136
+ st.sidebar.subheader("Instructions")
137
+ st.sidebar.write(
138
+ "1. Enter your OpenAI API Key in the sidebar.\n"
139
+ "2. Use the sidebar to choose an action: ask a question, view previous conversations, view the data summary, or save a note.\n"
140
+ "3. If you ask a question and click save, the conversation will be saved. If you ask multiple questions and then press save, it will save the whole conversation.\n"
141
+ "4. The End Conversation button will simply end the conversation without saving anything.\n"
142
+ )