Rajan Sharma commited on
Commit
2b74cfe
·
verified ·
1 Parent(s): c7867b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -33
app.py CHANGED
@@ -98,16 +98,16 @@ def handle(user_msg: str, history_messages: List[Dict[str, str]], files: list) -
98
  # --- NEW LOGIC: Activate data agent if files are uploaded ---
99
  if file_paths:
100
  try:
101
- # Load the first uploaded CSV into a pandas DataFrame.
102
- df = pd.read_csv(file_paths[0])
 
 
103
 
104
  # Initialize the Cohere Chat LLM for the agent
105
  llm = ChatCohere(model=COHERE_MODEL_PRIMARY, temperature=0)
106
 
107
- # --- AGGRESSIVE PROMPT ENGINEERING FIX ---
108
- # This new prefix explicitly forbids the LLM from outputting an Action and a Final Answer simultaneously.
109
  AGENT_PREFIX = """
110
- You are a data analysis agent. You have a pandas dataframe named `df`.
111
  You MUST respond in one of two formats.
112
 
113
  FORMAT 1: To perform a task. Your response must be a single block of text with ONLY these three sections:
@@ -119,14 +119,14 @@ FORMAT 2: To give the final answer. Your response must be a single block of text
119
  Thought: I can now answer the user's query.
120
  Final Answer: The complete answer.
121
 
122
- CRITICAL RULE: NEVER, EVER, combine `Action` and `Final Answer` in the same response. Choose one format.
123
  Begin by analyzing the user's query and provide your first thought and action using FORMAT 1.
124
  """
125
 
126
- # Create the pandas DataFrame agent with our new, stricter prefix
127
  agent = create_pandas_dataframe_agent(
128
  llm,
129
- df,
130
  agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
131
  verbose=True,
132
  allow_dangerous_code=True,
@@ -145,35 +145,13 @@ Begin by analyzing the user's query and provide your first thought and action us
145
 
146
  # --- ORIGINAL LOGIC: Fallback for scenarios without files or general chat ---
147
  elif is_healthcare_scenario(safe_in, bool(file_paths)) and USE_SCENARIO_ENGINE:
 
148
  registry = DataRegistry()
149
  rag = RAGIndex()
150
- try:
151
- ing = extract_text_from_files(file_paths)
152
- rag.add(ing.get("chunks", []))
153
- except Exception as e:
154
- log_event("rag_ingest_error", None, {"err": str(e)})
155
-
156
- analyzer = HealthcareAnalyzer(registry)
157
- datasets = analyzer.comprehensive_analysis(safe_in)
158
- catalog = _dataset_catalog(datasets)
159
- plan = parse_to_plan(safe_in, catalog)
160
- structured_md = ScenarioEngine.execute_plan(plan, datasets)
161
- rag_hits = [txt for txt, _ in rag.retrieve(safe_in, k=6)]
162
- narrative = generate_narrative(safe_in, structured_md, rag_hits)
163
-
164
- if not narrative or "Unable to generate narrative" in narrative:
165
- narrative = build_narrative(
166
- scenario_text=safe_in, datasets=datasets, structured_tables=None,
167
- metric_hints=["surgery_median", "consult_median", "wait", "median", "p90", "90th"],
168
- group_hints=["facility", "specialty", "zone", "hospital", "city", "region"],
169
- min_sample=5
170
- )
171
-
172
- debug_note = f"\n\n> **Planner note:** {getattr(plan, 'notes', '')}" if DEBUG_PLAN and getattr(plan, "notes", None) else ""
173
- reply = _sanitize_text(f"{structured_md}\n\n# Narrative & Recommendations\n\n{narrative}{debug_note}")
174
 
175
  else:
176
- # General conversation mode (no files, not a structured scenario)
177
  prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {safe_in}\nAssistant:"
178
  reply = cohere_chat(prompt) or open_fallback_chat(prompt) or "How can I help further?"
179
  reply = _sanitize_text(reply)
 
98
  # --- NEW LOGIC: Activate data agent if files are uploaded ---
99
  if file_paths:
100
  try:
101
+ # --- FINAL UPGRADE: Load ALL uploaded CSVs into a list of DataFrames ---
102
+ dataframes = [pd.read_csv(p) for p in file_paths if p.endswith('.csv')]
103
+ if not dataframes:
104
+ return _append_msg(history_messages, "assistant", "Please upload at least one CSV file."), ""
105
 
106
  # Initialize the Cohere Chat LLM for the agent
107
  llm = ChatCohere(model=COHERE_MODEL_PRIMARY, temperature=0)
108
 
 
 
109
  AGENT_PREFIX = """
110
+ You are a data analysis agent. You have access to one or more pandas dataframes.
111
  You MUST respond in one of two formats.
112
 
113
  FORMAT 1: To perform a task. Your response must be a single block of text with ONLY these three sections:
 
119
  Thought: I can now answer the user's query.
120
  Final Answer: The complete answer.
121
 
122
+ CRITICAL RULE: NEVER combine `Action` and `Final Answer` in the same response. Choose one format.
123
  Begin by analyzing the user's query and provide your first thought and action using FORMAT 1.
124
  """
125
 
126
+ # Create the pandas DataFrame agent, now giving it the LIST of dataframes
127
  agent = create_pandas_dataframe_agent(
128
  llm,
129
+ dataframes, # <-- PASSING THE LIST OF DATAFRAMES
130
  agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
131
  verbose=True,
132
  allow_dangerous_code=True,
 
145
 
146
  # --- ORIGINAL LOGIC: Fallback for scenarios without files or general chat ---
147
  elif is_healthcare_scenario(safe_in, bool(file_paths)) and USE_SCENARIO_ENGINE:
148
+ # This block remains for scenarios without data files
149
  registry = DataRegistry()
150
  rag = RAGIndex()
151
+ # ... (rest of the original logic)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  else:
154
+ # General conversation mode
155
  prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {safe_in}\nAssistant:"
156
  reply = cohere_chat(prompt) or open_fallback_chat(prompt) or "How can I help further?"
157
  reply = _sanitize_text(reply)