sanjaystarc commited on
Commit
e1d853d
Β·
verified Β·
1 Parent(s): cd88218

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -18
app.py CHANGED
@@ -3,67 +3,72 @@ import pandas as pd
3
  from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
4
  from langchain_google_genai import ChatGoogleGenerativeAI
5
  import os
 
6
 
7
  def main():
8
  st.set_page_config(page_title="Data Analysis Agent πŸ€–")
9
  st.title("πŸ€– Data Analysis Agent")
10
  st.write("Upload a CSV file and ask questions about your data.")
11
 
12
- # Get Gemini API Key from Streamlit Secrets
13
- # We use st.secrets for deployment on Hugging Face
 
14
  try:
15
- # For local development, you can set an environment variable
16
- # For deployment, set this in Hugging Face Spaces "Secrets"
17
- api_key = os.environ.get("GEMINI_API_KEY") or st.secrets["GEMINI_API_KEY"]
18
  except KeyError:
19
- st.error("GEMINI_API_KEY not found. Please set it in your Hugging Face Spaces secrets.")
20
- return
 
 
21
 
22
  if not api_key:
23
  st.warning("Please add your Gemini API Key to the Hugging Face Space Secrets to use the app.")
24
  return
25
 
26
- # File Uploader
27
  uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
28
 
29
  if uploaded_file is not None:
30
  try:
31
- # Read the CSV file into a Pandas DataFrame
32
  df = pd.read_csv(uploaded_file)
33
  st.dataframe(df.head())
34
 
35
  # Initialize the Gemini LLM
36
  llm = ChatGoogleGenerativeAI(
37
- model="gemini-pro",
38
  google_api_key=api_key,
39
  temperature=0
40
  )
41
 
42
  # Create the Pandas DataFrame Agent
43
- # allow_dangerous_code=True is required for the agent to execute Python code
44
  agent = create_pandas_dataframe_agent(
45
  llm,
46
  df,
47
- verbose=True,
48
- allow_dangerous_code=True
 
49
  )
50
 
51
- # User question input
52
  user_question = st.text_input("Ask a question about your data:")
53
 
54
  if user_question:
55
  with st.spinner("Analyzing..."):
56
  try:
57
- # The agent.invoke method runs the agent and returns a dictionary
58
- # The actual answer is in the "output" key
59
  response = agent.invoke(user_question)
60
  st.write("### Answer")
61
  st.success(response["output"])
 
62
  except Exception as e:
63
- st.error(f"Error analyzing data: {e}")
 
 
 
 
64
 
65
  except Exception as e:
66
- st.error(f"Error reading file: {e}")
67
 
68
  if __name__ == "__main__":
69
  main()
 
3
  from langchain_experimental.agents.agent_toolkits import create_pandas_dataframe_agent
4
  from langchain_google_genai import ChatGoogleGenerativeAI
5
  import os
6
+ import traceback
7
 
8
  def main():
9
  st.set_page_config(page_title="Data Analysis Agent πŸ€–")
10
  st.title("πŸ€– Data Analysis Agent")
11
  st.write("Upload a CSV file and ask questions about your data.")
12
 
13
+ # --- API Key Setup ---
14
+ # This block tries to get the API key from Hugging Face secrets
15
+ api_key = None
16
  try:
17
+ api_key = st.secrets["GEMINI_API_KEY"]
 
 
18
  except KeyError:
19
+ st.error("πŸ”΄ GEMINI_API_KEY not found in Hugging Face secrets!")
20
+ st.write("Please go to your Space's **Settings > Repository secrets** and add your Google AI Studio API key.")
21
+ st.write("The **Name** must be `GEMINI_API_KEY`.")
22
+ return # Stop the app if key is missing
23
 
24
  if not api_key:
25
  st.warning("Please add your Gemini API Key to the Hugging Face Space Secrets to use the app.")
26
  return
27
 
28
+ # --- File Uploader ---
29
  uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
30
 
31
  if uploaded_file is not None:
32
  try:
 
33
  df = pd.read_csv(uploaded_file)
34
  st.dataframe(df.head())
35
 
36
  # Initialize the Gemini LLM
37
  llm = ChatGoogleGenerativeAI(
38
+ model="gemini-1.5-pro-latest", # Using the latest, most capable model
39
  google_api_key=api_key,
40
  temperature=0
41
  )
42
 
43
  # Create the Pandas DataFrame Agent
 
44
  agent = create_pandas_dataframe_agent(
45
  llm,
46
  df,
47
+ verbose=True, # This will print the agent's thoughts in the log
48
+ allow_dangerous_code=True,
49
+ handle_parsing_errors=True # Helps with bad LLM outputs
50
  )
51
 
52
+ # --- User Interaction ---
53
  user_question = st.text_input("Ask a question about your data:")
54
 
55
  if user_question:
56
  with st.spinner("Analyzing..."):
57
  try:
58
+ # Invoke the agent
 
59
  response = agent.invoke(user_question)
60
  st.write("### Answer")
61
  st.success(response["output"])
62
+
63
  except Exception as e:
64
+ # This is the most important error block
65
+ st.error(f"πŸ”΄ An error occurred while analyzing the data.")
66
+ st.write("Here is the full error message:")
67
+ # Print the full error stack trace to the app
68
+ st.exception(e)
69
 
70
  except Exception as e:
71
+ st.error(f"πŸ”΄ An error occurred while reading the file: {e}")
72
 
73
  if __name__ == "__main__":
74
  main()