#!/usr/bin/env python3 """Public Gradio Space: Data Analyst + Chat with Your Spreadsheet, with session caps.""" from __future__ import annotations import spaces # ZeroGPU: must import before any CUDA-touching libraries import tempfile from pathlib import Path import gradio as gr from analyst.agent import AnalystAgent, _ensure_env from spreadsheet_chat.agent import SpreadsheetChat from spreadsheet_chat.datasets import BUSINESS_DIR, SAMPLES ROOT = Path(__file__).resolve().parent OUTPUT_DIR = Path(tempfile.gettempdir()) / "ai-data-analyst-runs" OUTPUT_DIR.mkdir(parents=True, exist_ok=True) DEFAULT_CSV = ROOT / "data" / "florida_health_plan_premiums_sample.csv" MAX_QUESTIONS_PER_SESSION = 20 SAMPLE_QUESTIONS = [ "Which Florida county has the highest average ACA Silver monthly premium?", "Compare average Medicare Advantage monthly premiums by county in a bar chart.", "What is the average ACA monthly premium by metal level statewide?", ] SAMPLE_PATHS = { key: BUSINESS_DIR / f"{meta['stem']}.{meta['format']}" for key, meta in SAMPLES.items() } SAMPLE_LABELS = {meta["title"]: key for key, meta in SAMPLES.items()} INTRO = """ # AI Data Analyst Agent Ask a plain-English question about a spreadsheet. A free model writes Python; the code runs in an isolated [E2B](https://e2b.dev) sandbox that is shut down afterward. Sample files are fictional — no real customers, patients, or members. This is a demo, not insurance or business advice. Please do not upload personal or client data. **Session limit:** {max_q} questions per visit, with a short sandbox timeout, so the public demo stays available. This Space uses Hugging Face's free ZeroGPU hosting (a Gradio Space on CPU Basic currently requires a PRO plan). Visitors also have a daily ZeroGPU time allowance. """.format(max_q=MAX_QUESTIONS_PER_SESSION) def _quota_label(state: dict | None) -> str: used = int((state or {}).get("used", 0)) left = max(0, MAX_QUESTIONS_PER_SESSION - used) return f"Questions this session: **{used}** / {MAX_QUESTIONS_PER_SESSION} ({left} left)." def _consume(state: dict | None) -> dict: state = dict(state or {}) used = int(state.get("used", 0)) if used >= MAX_QUESTIONS_PER_SESSION: raise gr.Error( f"This session has reached the demo limit of {MAX_QUESTIONS_PER_SESSION} questions. " "Reload the page to start a new session. The cap keeps the public demo available." ) state["used"] = used + 1 return state @spaces.GPU(duration=90) def analyze(csv_file, question: str, state: dict | None): _ensure_env() question = (question or "").strip() if not question: raise gr.Error("Please enter a question.") state = _consume(state) if csv_file is None: csv_path = DEFAULT_CSV else: csv_path = Path(csv_file.name if hasattr(csv_file, "name") else csv_file) result = AnalystAgent().analyze(csv_path, question, OUTPUT_DIR) detail = result.answer if result.retried: detail += "\n\n(The agent retried once after a sandbox error.)" if result.error: detail += f"\n\nSandbox error:\n{result.error}" detail += f"\n\nModel: {result.model}" chart = str(result.chart_path) if result.chart_path else None return detail, chart, state, _quota_label(state) @spaces.GPU(duration=30) def load_sheet(sample_label: str, upload, state: dict | None): _ensure_env() state = dict(state or {}) if upload is not None: path = Path(upload.name if hasattr(upload, "name") else upload) name = "upload-" + path.stem synthetic = False elif sample_label and sample_label in SAMPLE_LABELS: key = SAMPLE_LABELS[sample_label] path = SAMPLE_PATHS[key] name = key synthetic = True else: raise gr.Error("Choose a sample spreadsheet or upload a CSV/XLSX.") if not path.is_file(): raise gr.Error(f"File not found: {path}") state["session"] = SpreadsheetChat(path, OUTPUT_DIR, session_name=name) state["messages"] = [] notice = f"Loaded **{path.name}**. Ask a question about the columns in this sheet." if synthetic: notice += " This file is synthetic sample data, not a real business." return notice, state, None, _quota_label(state) @spaces.GPU(duration=90) def chat_ask(message: str, state: dict | None): _ensure_env() message = (message or "").strip() if not message: raise gr.Error("Type a question first.") if not state or "session" not in state: raise gr.Error("Load a sample or upload a spreadsheet first.") state = _consume(state) chat: SpreadsheetChat = state["session"] result = chat.ask(message) answer = result.answer if result.retried: answer += "\n\n(The agent retried once after a sandbox error.)" if result.error: answer += f"\n\nSandbox error:\n{result.error}" messages = list(state.get("messages") or []) messages.append({"role": "user", "content": message}) messages.append({"role": "assistant", "content": answer}) state["messages"] = messages chart = str(result.chart_path) if result.chart_path else None return messages, state, chart, "", _quota_label(state) def build_ui() -> gr.Blocks: with gr.Blocks(title="AI Data Analyst Agent") as demo: state = gr.State({}) gr.Markdown(INTRO) quota = gr.Markdown(_quota_label({})) with gr.Tabs(): with gr.Tab("Data Analyst"): gr.Markdown( "Upload a CSV, or leave it empty to use the included synthetic " "Florida health-plan premium sample." ) with gr.Row(): csv_in = gr.File( label="CSV file (optional — uses the sample if empty)", file_types=[".csv"], ) question = gr.Textbox( label="Question", lines=2, placeholder=SAMPLE_QUESTIONS[0], ) analyze_btn = gr.Button("Analyze", variant="primary") gr.Examples(examples=[[q] for q in SAMPLE_QUESTIONS], inputs=[question]) answer = gr.Textbox(label="Answer", lines=8) analyst_chart = gr.Image(label="Chart", type="filepath") analyze_btn.click( analyze, inputs=[csv_in, question, state], outputs=[answer, analyst_chart, state, quota], api_name="analyze", ) with gr.Tab("Chat with Your Spreadsheet"): gr.Markdown( "Start from a synthetic small-business sample, or upload your own " "CSV or Excel file (no personal or client data)." ) with gr.Row(): sample = gr.Dropdown( label="Synthetic sample", choices=list(SAMPLE_LABELS.keys()), value=list(SAMPLE_LABELS.keys())[0], ) upload = gr.File( label="Or upload CSV / XLSX", file_types=[".csv", ".xlsx", ".xls"], ) load_btn = gr.Button("Load spreadsheet", variant="primary") status = gr.Markdown("Load a spreadsheet to start chatting.") chatbot = gr.Chatbot(label="Conversation", height=420) chat_chart = gr.Image(label="Latest chart", type="filepath") chat_q = gr.Textbox( label="Question", placeholder="e.g. Which hour of the day has the most missed calls?", ) ask_btn = gr.Button("Ask", variant="primary") load_btn.click( load_sheet, inputs=[sample, upload, state], outputs=[status, state, chat_chart, quota], api_name="load_sheet", ) ask_btn.click( chat_ask, inputs=[chat_q, state], outputs=[chatbot, state, chat_chart, chat_q, quota], api_name="chat_ask", ) chat_q.submit( chat_ask, inputs=[chat_q, state], outputs=[chatbot, state, chat_chart, chat_q, quota], ) gr.Markdown( "Source: [github.com/larrybuckalew/ai-data-analyst-agent]" "(https://github.com/larrybuckalew/ai-data-analyst-agent)." ) return demo demo = build_ui() demo.queue(max_size=16) if __name__ == "__main__": demo.launch()