sanjaystarc commited on
Commit
ed21fd7
Β·
verified Β·
1 Parent(s): 9fa3482

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -70
app.py CHANGED
@@ -1,74 +1,58 @@
 
1
  import streamlit as st
2
  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
- 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()
 
1
+ import os
2
  import streamlit as st
3
  import pandas as pd
4
+ import numpy as np
5
+ import requests
6
+
7
+ # --- CONFIG ---
8
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
9
+ if not GEMINI_API_KEY:
10
+ st.error("❌ Missing Gemini API key. Add it as a secret: GEMINI_API_KEY")
11
+ st.stop()
12
+
13
+ GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta"
14
+ CHAT_MODEL = "models/gemini-1.5-flash"
15
+ EMBED_MODEL = "models/embedding-001"
16
+
17
+ # --- Helper Functions ---
18
+ def get_embedding(text):
19
+ url = f"{GEMINI_BASE}/{EMBED_MODEL}:embedText?key={GEMINI_API_KEY}"
20
+ data = {"text": text}
21
+ r = requests.post(url, json=data)
22
+ r.raise_for_status()
23
+ return r.json()["embedding"]["value"]
24
+
25
+ def chat_with_gemini(prompt, context=""):
26
+ url = f"{GEMINI_BASE}/{CHAT_MODEL}:generateContent?key={GEMINI_API_KEY}"
27
+ payload = {
28
+ "contents": [
29
+ {"parts": [{"text": f"{context}\n\nUser question: {prompt}"}]}
30
+ ]
31
+ }
32
+ r = requests.post(url, json=payload)
33
+ r.raise_for_status()
34
+ data = r.json()
35
+ return data["candidates"][0]["content"]["parts"][0]["text"]
36
+
37
+ # --- UI ---
38
+ st.title("πŸ“Š Data Analyst Agent (Gemini + Streamlit)")
39
+ st.write("Upload a CSV file and ask natural language questions about your data.")
40
+
41
+ uploaded = st.file_uploader("Upload CSV", type=["csv"])
42
+
43
+ if uploaded:
44
+ df = pd.read_csv(uploaded)
45
+ st.dataframe(df.head())
46
+
47
+ question = st.text_input("Ask a question about your data:")
48
+ if st.button("Analyze") and question:
49
+ # Summarize dataset for context
50
+ summary = f"Columns: {', '.join(df.columns)}. Example rows:\n{df.head(3).to_string(index=False)}"
51
  try:
52
+ response = chat_with_gemini(question, summary)
53
+ st.markdown("### πŸ’¬ Gemini Answer:")
54
+ st.write(response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  except Exception as e:
56
+ st.error(f"Error: {e}")
57
+ else:
58
+ st.info("πŸ‘† Upload a CSV file to begin.")