sanjaystarc commited on
Commit
d909df5
·
verified ·
1 Parent(s): 14ffeef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -18
app.py CHANGED
@@ -3,6 +3,8 @@ import streamlit as st
3
  import pandas as pd
4
  import matplotlib.pyplot as plt
5
  import seaborn as sns
 
 
6
 
7
  # Updated LangChain Imports
8
  from langchain_google_genai import ChatGoogleGenerativeAI
@@ -48,13 +50,14 @@ def main():
48
  query = st.text_area("What analysis would you like to perform?", placeholder="e.g., 'Plot the distribution of prices.'")
49
 
50
  if st.button("Run Agent") and query:
 
51
  llm = ChatGoogleGenerativeAI(
52
  model="gemini-2.5-flash-preview-09-2025",
53
  google_api_key=GEMINI_API_KEY,
54
  temperature=0,
 
55
  )
56
 
57
- # CUSTOM PROMPT PREFIX: Helps Gemini follow the ReAct format strictly to avoid parsing errors
58
  custom_prefix = """
59
  You are working with a pandas dataframe in Python. The name of the dataframe is `df`.
60
  You should use the tools below to answer the question posed of you.
@@ -62,9 +65,6 @@ def main():
62
  Do not wrap the code in markdown code blocks within the Action Input.
63
  """
64
 
65
- # Create the Pandas Agent with enhanced error handling
66
- # Fix: Pass 'handle_parsing_errors' directly and avoid passing 'max_iterations'
67
- # inside agent_executor_kwargs if it conflicts with the toolkit's defaults.
68
  agent = create_pandas_dataframe_agent(
69
  llm,
70
  df,
@@ -73,8 +73,6 @@ def main():
73
  allow_dangerous_code=True,
74
  prefix=custom_prefix,
75
  handle_parsing_errors=True,
76
- # We omit agent_executor_kwargs here to resolve the TypeError
77
- # as the function already handles execution parameters internally.
78
  )
79
 
80
  # --- 4. EXECUTION ---
@@ -83,19 +81,30 @@ def main():
83
  st_callback = StreamlitCallbackHandler(thought_container)
84
 
85
  with st.spinner("Agent is analyzing..."):
86
- try:
87
- # Run the loop
88
- response = agent.run(query, callbacks=[st_callback])
 
 
 
 
 
 
89
 
90
- st.markdown("---")
91
- st.subheader(" Final Analysis Result")
92
- st.success(response)
93
-
94
- except Exception as e:
95
- st.error(f"Agent failed to complete the task.")
96
- with st.expander("Show Technical Error"):
97
- st.code(str(e))
98
- st.info("💡 Tip: The agent had trouble formatting its 'Action'. Try asking the question again or rephrasing it.")
 
 
 
 
 
99
  else:
100
  st.info("👆 Upload a CSV to begin.")
101
 
 
3
  import pandas as pd
4
  import matplotlib.pyplot as plt
5
  import seaborn as sns
6
+ import time
7
+ import random
8
 
9
  # Updated LangChain Imports
10
  from langchain_google_genai import ChatGoogleGenerativeAI
 
50
  query = st.text_area("What analysis would you like to perform?", placeholder="e.g., 'Plot the distribution of prices.'")
51
 
52
  if st.button("Run Agent") and query:
53
+ # Initialize LLM with max_retries at the model level
54
  llm = ChatGoogleGenerativeAI(
55
  model="gemini-2.5-flash-preview-09-2025",
56
  google_api_key=GEMINI_API_KEY,
57
  temperature=0,
58
+ max_retries=6, # LangChain's built-in retry logic
59
  )
60
 
 
61
  custom_prefix = """
62
  You are working with a pandas dataframe in Python. The name of the dataframe is `df`.
63
  You should use the tools below to answer the question posed of you.
 
65
  Do not wrap the code in markdown code blocks within the Action Input.
66
  """
67
 
 
 
 
68
  agent = create_pandas_dataframe_agent(
69
  llm,
70
  df,
 
73
  allow_dangerous_code=True,
74
  prefix=custom_prefix,
75
  handle_parsing_errors=True,
 
 
76
  )
77
 
78
  # --- 4. EXECUTION ---
 
81
  st_callback = StreamlitCallbackHandler(thought_container)
82
 
83
  with st.spinner("Agent is analyzing..."):
84
+ # Manual retry logic wrapper for the whole agentic loop
85
+ max_loop_retries = 3
86
+ for attempt in range(max_loop_retries):
87
+ try:
88
+ response = agent.run(query, callbacks=[st_callback])
89
+ st.markdown("---")
90
+ st.subheader("✅ Final Analysis Result")
91
+ st.success(response)
92
+ break # Exit loop if successful
93
 
94
+ except Exception as e:
95
+ if "429" in str(e) or "RESOURCE_EXHAUSTED" in str(e):
96
+ if attempt < max_loop_retries - 1:
97
+ wait_time = (2 ** attempt) + random.random()
98
+ st.warning(f"Quota reached. Retrying in {wait_time:.2f} seconds...")
99
+ time.sleep(wait_time)
100
+ continue
101
+ else:
102
+ st.error("Rate limit exceeded consistently. Please try again in a minute.")
103
+ else:
104
+ st.error(f"Agent failed to complete the task.")
105
+ with st.expander("Show Technical Error"):
106
+ st.code(str(e))
107
+ break
108
  else:
109
  st.info("👆 Upload a CSV to begin.")
110