Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/bandimeharchaitanya_legacy-x-hackathon.json

1 line
5.9 KiB
JSON

{"repo": "bandimeharchaitanya/legacy-x-hackathon", "files": {"main.py": {"655569e5c21f5b4dd42eae1f3f228ba7493105bd": {"t": 1785674056.3817348, "n": 5534, "h": "8a01b102c24a249f", "c": "\"\"\"\nmain.py\n-------\nThin FastAPI wrapper around agent.ask_question(). This is what the React\nfrontend talks to over HTTP -- nothing fancy, just enough to demo.\n\nRun:\n pip install fastapi uvicorn --break-system-packages\n export DEEPSEEK_API_KEY=\"sk-...\"\n uvicorn main:app --reload --host 0.0.0.0 --port 8000\n\nThen test it's alive:\n curl http://localhost:8000/health\n\nAnd ask a question:\n curl -X POST http://localhost:8000/query \\\n -H \"Content-Type: application/json\" \\\n -d '{\"question\": \"Show me Q3 revenue by region vs last year\"}'\n\"\"\"\n\nfrom fastapi import FastAPI, HTTPException\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.responses import FileResponse\nfrom pydantic import BaseModel\nimport sqlite3\nimport time\nimport os\n\nfrom agent import ask_question, AgentError, BudgetExceededError, DB_PATH, get_cost_summary\n\napp = FastAPI(title=\"Legacy X — Conversational Reporting API\")\n\n# Wide-open CORS for hackathon purposes only. Fine for a 3-day demo on a\n# sandbox VM with no real users; do NOT carry this setting into anything\n# resembling production.\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nSTATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"static\")\n\n\nclass QueryRequest(BaseModel):\n question: str\n\n\nclass QueryResponse(BaseModel):\n question: str\n sql: str\n rows: list\n row_count: int\n insight: str\n chart_type: str\n elapsed_seconds: float\n cumulative_cost_usd: float\n cumulative_calls: int\n\n\n@app.get(\"/health\")\ndef health():\n \"\"\"Quick check that the API is up and the database file is reachable.\n Hit this first if anything looks broken during the demo.\"\"\"\n try:\n conn = sqlite3.connect(DB_PATH)\n count = conn.execute(\"SELECT COUNT(*) FROM orders\").fetchone()[0]\n conn.close()\n db_ok = True\n except Exception as e:\n count = None\n db_ok = False\n\n return {\n \"status\": \"ok\" if db_ok else \"degraded\",\n \"database_reachable\": db_ok,\n \"order_row_count\": count,\n }\n\n\n@app.get(\"/schema\")\ndef schema():\n \"\"\"Returns the table schema -- handy for the frontend team or for\n sanity-checking what columns/regions/products actually exist.\"\"\"\n conn = sqlite3.connect(DB_PATH)\n conn.row_factory = sqlite3.Row\n regions = [dict(r) for r in conn.execute(\"SELECT * FROM regions\").fetchall()]\n products = [dict(r) for r in conn.execute(\"SELECT * FROM products\").fetchall()]\n conn.close()\n return {\"regions\": regions, \"products\": products}\n\n\n@app.post(\"/query\", response_model=QueryResponse)\ndef query(payload: QueryRequest):\n \"\"\"Main endpoint: takes a natural language question, returns SQL,\n result rows, a one-line insight, a suggested chart type, and the\n running cumulative DeepSeek spend so far.\"\"\"\n question = payload.question.strip()\n if not question:\n raise HTTPException(status_code=400, detail=\"Question must not be empty.\")\n\n start = time.time()\n # Backstop env loading inside the server process.\n # uvicorn --reload can spawn subprocesses with different env inheritance,\n # so we ensure `.env` is loaded (best-effort) before touching the agent.\n env_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \".env\")\n if not os.environ.get(\"DEEPSEEK_API_KEY\") and os.path.exists(env_path):\n try:\n with open(env_path, \"r\", encoding=\"utf-8\") as f:\n for line in f:\n stripped = line.strip()\n if not stripped or stripped.startswith(\"#\") or \"=\" not in stripped:\n continue\n k, v = stripped.split(\"=\", 1)\n k = k.strip()\n v = v.strip().strip('\"').strip(\"'\")\n if k and not os.environ.get(k):\n os.environ[k] = v\n except OSError:\n pass\n\n try:\n result = ask_question(question)\n except BudgetExceededError as e:\n\n # Distinct from a generic AgentError so the frontend could show a\n # different message if desired (e.g. \"demo paused, check budget\").\n raise HTTPException(status_code=429, detail=str(e))\n except AgentError as e:\n # Surfaces cleanly to the frontend instead of a raw 500 -- useful\n # for showing a friendly \"couldn't process that\" message live.\n raise HTTPException(status_code=422, detail=str(e))\n except sqlite3.Error as e:\n raise HTTPException(status_code=500, detail=f\"Database error: {e}\")\n\n result[\"elapsed_seconds\"] = round(time.time() - start, 2)\n return result\n\n\n@app.get(\"/usage\")\ndef usage():\n \"\"\"Cumulative DeepSeek spend tracked from real token usage on every\n call, persisted across server restarts. Check this any time to see\n exactly how much of your $10 budget has actually been used.\"\"\"\n summary = get_cost_summary()\n return {\n **summary,\n \"budget_usd\": 10.00,\n \"percent_used\": round(summary[\"total_cost_usd\"] / 10.00 * 100, 4),\n }\n\n\n@app.get(\"/\")\ndef root():\n \"\"\"Serves the chat UI directly -- open http://localhost:8000 in a browser.\"\"\"\n index_path = os.path.join(STATIC_DIR, \"index.html\")\n return FileResponse(index_path)\n\n\n@app.get(\"/api\")\ndef api_info():\n return {\n \"message\": \"Legacy X Conversational Reporting API is running.\",\n \"endpoints\": [\"/health\", \"/schema\", \"/usage\", \"POST /query\"],\n }"}}}}