Rajan Sharma commited on
Commit
c098a9c
·
verified ·
1 Parent(s): fb8cb62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -8
app.py CHANGED
@@ -11,7 +11,8 @@ from datetime import datetime
11
 
12
  # --- BACKEND IMPORTS ---
13
  from langchain_cohere import ChatCohere
14
- from langchain_community.utilities.python import PythonREPL # Re-introducing the standard, robust executor
 
15
 
16
  # --- LOCAL MODULE IMPORTS ---
17
  from settings import (
@@ -38,11 +39,11 @@ def _sanitize_text(s: str) -> str:
38
 
39
  def _create_python_script(user_scenario: str, schema_context: str) -> str:
40
  """Uses an LLM to act as an "AI Coder", writing a complete Python script."""
41
- # --- THE FINAL PROMPT FIX IS HERE ---
42
  prompt_for_coder = f"""
43
  You are an expert Python data scientist. Your sole job is to write a single, complete, and executable Python script to answer the user's request.
44
- You have access to a list of pandas dataframes loaded into a variable named `dfs`.
45
 
 
46
  --- DATA SCHEMA ---
47
  {schema_context}
48
  --- END SCHEMA ---
@@ -52,8 +53,8 @@ CRITICAL RULE: You MUST use the exact column names provided in the DATA SCHEMA.
52
  Based on the user's scenario below, write a single Python script that performs the entire analysis.
53
 
54
  RULES FOR YOUR SCRIPT:
55
- 1. **Use the DataFrames:** Your script MUST use the `dfs` list and the exact column names from the schema.
56
- 2. **Print Your Findings:** Use the `print()` function at each step to output the results as a formatted report.
57
  3. **No Placeholders:** Do not use placeholder data.
58
  4. **Self-Contained:** The script must be entirely self-contained.
59
 
@@ -80,7 +81,7 @@ def ping_cohere() -> str:
80
  cli = _co_client()
81
  if not cli: return "Cohere client not initialized."
82
  vecs = cohere_embed(["hello", "world"])
83
- return f"Cohere OK ✅ (model={COHERE_MODEL_PRIMARY})" if vecs else "Cohere reachable."
84
  except Exception as e:
85
  return f"Cohere ping failed: {e}"
86
 
@@ -111,12 +112,17 @@ def handle(user_msg: str, files: list) -> str:
111
  schema_context = "\n".join(schema_parts)
112
  analysis_script = _create_python_script(safe_in, schema_context)
113
 
 
114
  python_repl = PythonREPL()
 
115
  local_vars = {"dfs": dataframes}
 
116
  try:
 
117
  res = python_repl.run(command=analysis_script, locals=local_vars)
118
  return _sanitize_text(res)
119
  except Exception as e:
 
120
  return f"An error occurred executing the script: {e}\n\nGenerated Script:\n```python\n{analysis_script}\n```"
121
  else:
122
  prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {safe_in}\nAssistant:"
@@ -176,7 +182,7 @@ with gr.Blocks(theme="soft", css="style.css") as demo:
176
  return
177
 
178
  chat_with_user_msg = _append_msg(chat_history_list, "user", prompt)
179
- thinking_message = _append_msg(chat_with_user_msg, "assistant", "```\n🧠 Generating analysis script... This may take a moment.\n```")
180
  yield thinking_message, history_state_list, gr.update()
181
 
182
  ai_response_text = handle(prompt, files)
@@ -191,7 +197,7 @@ with gr.Blocks(theme="soft", css="style.css") as demo:
191
 
192
  def view_history(selection, history_state_list):
193
  if not selection or not history_state_list: return ""
194
- selected_id = selection.split(" - ")
195
  selected_assessment = next((item for item in history_state_list if item["id"] == selected_id), None)
196
  if selected_assessment:
197
  file_list_md = "\n- ".join(selected_assessment['files'])
 
11
 
12
  # --- BACKEND IMPORTS ---
13
  from langchain_cohere import ChatCohere
14
+ # --- THE FIXED IMPORT IS HERE ---
15
+ from langchain_experimental.utilities.python import PythonREPL
16
 
17
  # --- LOCAL MODULE IMPORTS ---
18
  from settings import (
 
39
 
40
  def _create_python_script(user_scenario: str, schema_context: str) -> str:
41
  """Uses an LLM to act as an "AI Coder", writing a complete Python script."""
 
42
  prompt_for_coder = f"""
43
  You are an expert Python data scientist. Your sole job is to write a single, complete, and executable Python script to answer the user's request.
44
+ You have access to a list of pandas dataframes loaded into a variable named `dfs`. The first dataframe is `dfs[0]`, the second is `dfs[1]`, and so on.
45
 
46
+ CRITICAL CONTEXT: Before writing any code, you MUST first understand the data you have been given. Here is the schema for each dataframe:
47
  --- DATA SCHEMA ---
48
  {schema_context}
49
  --- END SCHEMA ---
 
53
  Based on the user's scenario below, write a single Python script that performs the entire analysis.
54
 
55
  RULES FOR YOUR SCRIPT:
56
+ 1. **Use the DataFrames:** Your script MUST use the `dfs` list to access the data.
57
+ 2. **Print Your Findings:** Use the `print()` function at each step of your analysis to output the results as a formatted report.
58
  3. **No Placeholders:** Do not use placeholder data.
59
  4. **Self-Contained:** The script must be entirely self-contained.
60
 
 
81
  cli = _co_client()
82
  if not cli: return "Cohere client not initialized."
83
  vecs = cohere_embed(["hello", "world"])
84
+ return f"Cohere OK ✅ (model={COHERE_MODEL_PRIMARY}, timeout={COHERE_TIMEOUT_S}s)" if vecs else "Cohere reachable."
85
  except Exception as e:
86
  return f"Cohere ping failed: {e}"
87
 
 
112
  schema_context = "\n".join(schema_parts)
113
  analysis_script = _create_python_script(safe_in, schema_context)
114
 
115
+ # Initialize the Python Executor
116
  python_repl = PythonREPL()
117
+ # Pass the dataframes into the execution environment
118
  local_vars = {"dfs": dataframes}
119
+
120
  try:
121
+ # Execute the AI-generated script
122
  res = python_repl.run(command=analysis_script, locals=local_vars)
123
  return _sanitize_text(res)
124
  except Exception as e:
125
+ # If execution fails, return the error and the script for debugging
126
  return f"An error occurred executing the script: {e}\n\nGenerated Script:\n```python\n{analysis_script}\n```"
127
  else:
128
  prompt = f"{GENERAL_CONVERSATION_PROMPT}\n\nUser: {safe_in}\nAssistant:"
 
182
  return
183
 
184
  chat_with_user_msg = _append_msg(chat_history_list, "user", prompt)
185
+ thinking_message = _append_msg(chat_with_user_msg, "assistant", "```\n🧠 Generating and executing analysis script... This may take a moment.\n```")
186
  yield thinking_message, history_state_list, gr.update()
187
 
188
  ai_response_text = handle(prompt, files)
 
197
 
198
  def view_history(selection, history_state_list):
199
  if not selection or not history_state_list: return ""
200
+ selected_id = selection.split(" - ")[0]
201
  selected_assessment = next((item for item in history_state_list if item["id"] == selected_id), None)
202
  if selected_assessment:
203
  file_list_md = "\n- ".join(selected_assessment['files'])