Spaces:
Running on Zero
Running on Zero
Download spreadsheet_chat/agent.py from BuckalewFinancial/ai-data-analyst-agent: direct link, hf CLI and curl.
- Browser
- Download file 9.75 kB
-
https://huggingface.co/spaces/BuckalewFinancial/ai-data-analyst-agent/resolve/main/spreadsheet_chat/agent.py
- Command line
-
hf download hf://spaces/BuckalewFinancial/ai-data-analyst-agent/spreadsheet_chat/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/BuckalewFinancial/ai-data-analyst-agent/resolve/main/spreadsheet_chat/agent.py
9.75 kB
| """Multi-turn spreadsheet Q&A. Each turn runs in a fresh E2B sandbox that is then killed.""" | |
| from __future__ import annotations | |
| import io | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| import pandas as pd | |
| from analyst.agent import ( | |
| CODE_TIMEOUT_S, | |
| SANDBOX_CHART, | |
| SANDBOX_TIMEOUT_S, | |
| _ensure_env, | |
| _extract_answer, | |
| _join_logs, | |
| _safe_slug, | |
| ) | |
| from analyst.llm import complete | |
| from e2b_code_interpreter import Sandbox | |
| SYSTEM_PROMPT = """You write Python for a data-analysis sandbox in a multi-turn conversation. | |
| The sandbox already has pandas, numpy, and matplotlib. Do not install packages. | |
| CSV files are already on disk. Paths are listed in the user message. | |
| If a chart would help, write it to CHART_PATH. | |
| Rules: | |
| - Reply with Python code only. No markdown fences, no commentary before or after. | |
| - Read only the files listed. Use pandas. If a column looks numeric but is stored as text, coerce it. Treat empty strings as missing. | |
| - Print exactly one line that starts with ANSWER: followed by a concise plain-English result (include key numbers and units). | |
| - You may print a few extra supporting lines after that if useful. | |
| - When a chart helps, create one with matplotlib. Title and label the axes. Call tight_layout(). Save it to CHART_PATH with dpi=140 and bbox_inches='tight'. Do not call plt.show(). Use matplotlib.use('Agg') before importing pyplot. | |
| - If the user asks a follow-up, build on the prior analysis rather than starting over blindly. | |
| - Do not invent columns or rows that are not in the files. | |
| - Do not access the internet. | |
| - This is a synthetic demo dataset. Do not make marketing claims or talk about real clients. | |
| """ | |
| class TurnResult: | |
| question: str | |
| answer: str | |
| code: str | |
| model: str | |
| chart_path: Path | None = None | |
| stdout: str = "" | |
| stderr: str = "" | |
| retried: bool = False | |
| error: str | None = None | |
| log_path: Path | None = None | |
| class PreparedFile: | |
| sandbox_path: str | |
| local_path: Path | |
| data: bytes | |
| profile: str | |
| def prepare_upload(file_path: Path) -> list[PreparedFile]: | |
| """Turn a CSV or XLSX into CSV bytes the sandbox can read, plus a column profile.""" | |
| file_path = file_path.expanduser().resolve() | |
| if not file_path.is_file(): | |
| raise FileNotFoundError(file_path) | |
| suffix = file_path.suffix.lower() | |
| prepared: list[PreparedFile] = [] | |
| if suffix == ".csv": | |
| df = pd.read_csv(file_path) | |
| profile = _profile_frame(df, "/home/user/data.csv") | |
| prepared.append( | |
| PreparedFile( | |
| sandbox_path="/home/user/data.csv", | |
| local_path=file_path, | |
| data=file_path.read_bytes(), | |
| profile=profile, | |
| ) | |
| ) | |
| return prepared | |
| if suffix in {".xlsx", ".xls"}: | |
| sheets = pd.read_excel(file_path, sheet_name=None) | |
| if not sheets: | |
| raise ValueError(f"No sheets found in {file_path}") | |
| for i, (name, df) in enumerate(sheets.items()): | |
| slug = _safe_slug(str(name)) or f"sheet{i+1}" | |
| sandbox_path = f"/home/user/data/{slug}.csv" | |
| buf = io.StringIO() | |
| df.to_csv(buf, index=False) | |
| profile = _profile_frame(df, sandbox_path) | |
| prepared.append( | |
| PreparedFile( | |
| sandbox_path=sandbox_path, | |
| local_path=file_path, | |
| data=buf.getvalue().encode("utf-8"), | |
| profile=profile, | |
| ) | |
| ) | |
| return prepared | |
| raise ValueError(f"Unsupported file type: {suffix}. Use CSV or XLSX.") | |
| def _profile_frame(df: pd.DataFrame, sandbox_path: str, max_rows: int = 5) -> str: | |
| buf = io.StringIO() | |
| buf.write(f"Path: {sandbox_path}\n") | |
| buf.write(f"Rows: {len(df)} Columns: {len(df.columns)}\n") | |
| buf.write("Columns and dtypes:\n") | |
| for col in df.columns: | |
| nonempty = df[col].replace("", pd.NA).notna().sum() | |
| buf.write(f" - {col} ({df[col].dtype}, {nonempty} non-empty)\n") | |
| buf.write("First rows:\n") | |
| buf.write(df.head(max_rows).to_csv(index=False)) | |
| return buf.getvalue() | |
| class SpreadsheetChat: | |
| """Ask follow-up questions about one uploaded spreadsheet.""" | |
| def __init__(self, file_path: str | Path, output_dir: str | Path, session_name: str | None = None): | |
| self.file_path = Path(file_path).expanduser().resolve() | |
| self.output_dir = Path(output_dir).expanduser().resolve() | |
| self.output_dir.mkdir(parents=True, exist_ok=True) | |
| self.session_name = session_name or _safe_slug(self.file_path.stem) | |
| self.prepared = prepare_upload(self.file_path) | |
| self.history: list[TurnResult] = [] | |
| def ask(self, question: str) -> TurnResult: | |
| _ensure_env() | |
| question = (question or "").strip() | |
| if not question: | |
| raise ValueError("Question is empty.") | |
| prompt = self._build_prompt(question) | |
| code, model = complete(prompt, system_prompt=SYSTEM_PROMPT) | |
| result = TurnResult(question=question, answer="", code=code, model=model) | |
| turn_no = len(self.history) + 1 | |
| sbx = None | |
| try: | |
| sbx = Sandbox.create(timeout=SANDBOX_TIMEOUT_S) | |
| written_dirs: set[str] = set() | |
| for item in self.prepared: | |
| parent = str(Path(item.sandbox_path).parent) | |
| if parent not in {"/home/user", "/"} and parent not in written_dirs: | |
| sbx.files.make_dir(parent) | |
| written_dirs.add(parent) | |
| sbx.files.write(item.sandbox_path, item.data) | |
| execution = sbx.run_code(code, timeout=CODE_TIMEOUT_S) | |
| stdout, stderr, err_text, err = _execution_bits(execution) | |
| if err or not stdout.strip(): | |
| result.retried = True | |
| repair_prompt = self._build_prompt(question, repair=(code, stdout, stderr, err_text)) | |
| code, model = complete(repair_prompt, system_prompt=SYSTEM_PROMPT) | |
| result.code = code | |
| result.model = model | |
| execution = sbx.run_code(code, timeout=CODE_TIMEOUT_S) | |
| stdout, stderr, err_text, err = _execution_bits(execution) | |
| result.stdout = stdout | |
| result.stderr = stderr | |
| result.answer = _extract_answer(stdout) | |
| if err: | |
| result.error = err_text.strip() | |
| if not result.answer: | |
| result.answer = "The sandbox code failed after one retry. See error details." | |
| if sbx.files.exists(SANDBOX_CHART): | |
| chart_path = self.output_dir / f"{self.session_name}-turn{turn_no:02d}.png" | |
| chart_path.write_bytes(sbx.files.read(SANDBOX_CHART, format="bytes")) | |
| result.chart_path = chart_path | |
| finally: | |
| if sbx is not None: | |
| try: | |
| sbx.kill() | |
| except Exception: | |
| pass | |
| log_path = self.output_dir / f"{self.session_name}-turn{turn_no:02d}.txt" | |
| log_path.write_text(_format_log(result), encoding="utf-8") | |
| result.log_path = log_path | |
| self.history.append(result) | |
| return result | |
| def _build_prompt(self, question: str, repair: tuple[str, str, str, str] | None = None) -> str: | |
| paths = ", ".join(item.sandbox_path for item in self.prepared) | |
| parts = [ | |
| "CHART_PATH = '/home/user/chart.png'", | |
| f"Data files: {paths}", | |
| "", | |
| "CSV profile:", | |
| ] | |
| for item in self.prepared: | |
| parts.append(item.profile) | |
| parts.append("") | |
| if self.history: | |
| parts.append("Earlier turns in this conversation:") | |
| for i, turn in enumerate(self.history, start=1): | |
| parts.append(f"Turn {i} question: {turn.question}") | |
| parts.append(f"Turn {i} answer: {turn.answer}") | |
| if turn.chart_path: | |
| parts.append(f"Turn {i} produced a chart.") | |
| parts.append("") | |
| parts.append("Current user question:") | |
| parts.append(question) | |
| if repair: | |
| prev_code, stdout, stderr, err_text = repair | |
| parts.extend( | |
| [ | |
| "", | |
| "The previous script failed. Fix it. Previous error and output:", | |
| "Previous Python:", | |
| prev_code, | |
| f"stdout:\n{stdout}", | |
| f"stderr:\n{stderr}", | |
| f"error:\n{err_text or 'No ANSWER: line and little or no stdout.'}", | |
| ] | |
| ) | |
| return "\n".join(parts) | |
| def _execution_bits(execution) -> tuple[str, str, str, object]: | |
| stdout = _join_logs(execution.logs.stdout if execution.logs else "") | |
| stderr = _join_logs(execution.logs.stderr if execution.logs else "") | |
| err = execution.error | |
| err_text = "" | |
| if err: | |
| err_text = f"{getattr(err, 'name', 'Error')}: {getattr(err, 'value', err)}\n" | |
| traceback = getattr(err, "traceback", "") | |
| if traceback: | |
| err_text += str(traceback) | |
| return stdout, stderr, err_text, err | |
| def _format_log(result: TurnResult) -> str: | |
| chart = str(result.chart_path) if result.chart_path else "(no chart file)" | |
| error = result.error or "(none)" | |
| return ( | |
| f"Question: {result.question}\n" | |
| f"Answer: {result.answer}\n" | |
| f"Model: {result.model}\n" | |
| f"Retried: {result.retried}\n" | |
| f"Chart: {chart}\n" | |
| f"Error: {error}\n\n" | |
| f"--- stdout ---\n{result.stdout}\n\n" | |
| f"--- stderr ---\n{result.stderr}\n\n" | |
| f"--- code ---\n{result.code}\n" | |
| ) | |