From 85eb33ec82cb96f3edaf60817f9bbe1f7d830b3c Mon Sep 17 00:00:00 2001 From: Patrick Donohoe Date: Thu, 3 Dec 2026 12:47:20 -0500 Subject: [PATCH] Prepare the LangChain hosting toolkit and weekly sales example --- .github/workflows/langchain-floo.yml | 54 ++++++++++++++ python/langchain-floo/README.md | 14 +++- .../examples/weekly-sales/app/Dockerfile | 6 ++ .../examples/weekly-sales/app/floo.app.toml | 19 +++++ .../examples/weekly-sales/app/report.html | 11 +++ .../examples/weekly-sales/app/report.py | 72 +++++++++++++++++++ .../weekly-sales/app/requirements.txt | 3 + .../examples/weekly-sales/app/sales.csv | 6 ++ .../examples/weekly-sales/deploy.py | 56 +++++++++++++++ 9 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/langchain-floo.yml create mode 100644 python/langchain-floo/examples/weekly-sales/app/Dockerfile create mode 100644 python/langchain-floo/examples/weekly-sales/app/floo.app.toml create mode 100644 python/langchain-floo/examples/weekly-sales/app/report.html create mode 100644 python/langchain-floo/examples/weekly-sales/app/report.py create mode 100644 python/langchain-floo/examples/weekly-sales/app/requirements.txt create mode 100644 python/langchain-floo/examples/weekly-sales/app/sales.csv create mode 100644 python/langchain-floo/examples/weekly-sales/deploy.py diff --git a/.github/workflows/langchain-floo.yml b/.github/workflows/langchain-floo.yml new file mode 100644 index 0000000..726167f --- /dev/null +++ b/.github/workflows/langchain-floo.yml @@ -0,0 +1,54 @@ +name: LangChain hosting toolkit + +on: + pull_request: + paths: + - "python/langchain-floo/**" + - ".github/workflows/langchain-floo.yml" + push: + tags: + - "langchain-floo-v*" + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + defaults: + run: + working-directory: python/langchain-floo + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 + with: + python-version: "3.13" + - if: github.ref_type == 'tag' + run: | + version=$(uv version --short) + test "$GITHUB_REF_NAME" = "langchain-floo-v${version}" + - run: | + uv build + uvx twine check --strict dist/* + uv venv --python 3.10 "$RUNNER_TEMP/test-env" + uv pip install --python "$RUNNER_TEMP/test-env/bin/python" dist/*.whl + "$RUNNER_TEMP/test-env/bin/python" -I -m unittest discover -s tests -v + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f + with: + name: python-dist + path: python/langchain-floo/dist/ + if-no-files-found: error + + publish: + if: github.repository == 'getfloo/floo-cli' && github.ref_type == 'tag' + needs: build + runs-on: ubuntu-latest + environment: langchain-floo-pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 + with: + name: python-dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 diff --git a/python/langchain-floo/README.md b/python/langchain-floo/README.md index bd563c2..5845d0a 100644 --- a/python/langchain-floo/README.md +++ b/python/langchain-floo/README.md @@ -1,6 +1,6 @@ # langchain-floo -Load floo tools into a Python LangChain agent. The tools use the permissions of the floo API key supplied by the application. +Give a Python LangChain agent tools to deploy apps on floo, check deploys and read runtime logs. The tools use the permissions of the floo API key supplied by the application. Install from this repository: @@ -26,4 +26,16 @@ asyncio.run(main()) Pass the returned tools to LangChain's `create_agent`. Omit `tool_names` to load all tools exposed by floo to that credential. To supply the key from your application's secret store, pass `api_key` to `load_floo_tools`. +## Deploy a weekly sales dashboard + +The [weekly sales example](https://github.com/getfloo/floo-cli/tree/main/python/langchain-floo/examples/weekly-sales) deploys a public dashboard with the same LangChain tools an agent receives. It saves one report per week in managed Postgres and refreshes it on Mondays at 09:00 UTC. The five sample rows total 33 units and 840 in revenue. + +From a checkout of this repository, with the package installed and `FLOO_KEY` and `FLOO_ORG_ID` set, run: + +```sh +python python/langchain-floo/examples/weekly-sales/deploy.py "sales-report-$(date +%s)" +``` + +The script creates a new dev app and prints its URL. Open the dashboard or append `/api/report` to read the stored snapshot, refresh count and timestamp. Hosting, Postgres and scheduled runs use your floo org’s credits. Delete the sample app after testing if you want to stop its resources. + [floo MCP guide](https://getfloo.com/docs/guides/mcp#langchain) diff --git a/python/langchain-floo/examples/weekly-sales/app/Dockerfile b/python/langchain-floo/examples/weekly-sales/app/Dockerfile new file mode 100644 index 0000000..fd1fa61 --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/app/Dockerfile @@ -0,0 +1,6 @@ +FROM python:3.13-slim +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY report.py report.html sales.csv ./ +CMD ["gunicorn", "--bind", "0.0.0.0:8000", "report:web"] diff --git a/python/langchain-floo/examples/weekly-sales/app/floo.app.toml b/python/langchain-floo/examples/weekly-sales/app/floo.app.toml new file mode 100644 index 0000000..da52374 --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/app/floo.app.toml @@ -0,0 +1,19 @@ +[app] +name = "langchain-sales-report" +access_mode = "public" + +[services.web] +type = "web" +path = "." +port = 8000 +ingress = "public" +migrate_command = "python report.py initialize" + +[managed.default] +type = "postgres" + +[cron.weekly-sales] +schedule = "0 9 * * 1" +command = "python report.py refresh" +service = "web" +timeout = 120 diff --git a/python/langchain-floo/examples/weekly-sales/app/report.html b/python/langchain-floo/examples/weekly-sales/app/report.html new file mode 100644 index 0000000..aa7d852 --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/app/report.html @@ -0,0 +1,11 @@ + + +Weekly sales report + +

Weekly sales report

Sample sales data · Snapshot for the week of {{ report.week }}

+
Units sold
{{ report.units }}
Revenue
{{ report.revenue }}
+ +{% for product in report.products %}{% endfor %} +
ProductUnitsRevenue
{{ product.name }}{{ product.units }}{{ product.revenue }}
diff --git a/python/langchain-floo/examples/weekly-sales/app/report.py b/python/langchain-floo/examples/weekly-sales/app/report.py new file mode 100644 index 0000000..00b1ecc --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/app/report.py @@ -0,0 +1,72 @@ +"""Persist one sales snapshot per week; serve the most recent one.""" +import csv +import os +import sys +from datetime import datetime, timedelta, timezone +from decimal import Decimal +from pathlib import Path + +import psycopg +from flask import Flask, jsonify, render_template +from psycopg.rows import dict_row +from psycopg.types.json import Jsonb + +ROOT = Path(__file__).resolve().parent +web = Flask(__name__, template_folder=str(ROOT)) + + +def connect(): + return psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) + + +def summarize(): + products = {} + with (ROOT / "sales.csv").open(newline="") as source: + for row in csv.DictReader(source): + item = products.setdefault(row["Product"], {"units": 0, "revenue": Decimal(0)}) + item["units"] += int(row["Units Sold"]) + item["revenue"] += Decimal(row["Revenue"]) + return [{"name": name, "units": item["units"], "revenue": str(item["revenue"])} + for name, item in sorted(products.items())] + + +def refresh(*, initialize=False): + products = summarize() + now = datetime.now(timezone.utc) + week = now.date() - timedelta(days=now.weekday()) + with connect() as db: + if initialize: + db.execute("""CREATE TABLE IF NOT EXISTS weekly_sales ( + week date PRIMARY KEY, refreshed_at timestamptz NOT NULL, + refreshes integer NOT NULL, products jsonb NOT NULL)""") + conflict = "DO NOTHING" if initialize else """DO UPDATE SET + products = EXCLUDED.products, refreshed_at = EXCLUDED.refreshed_at, + refreshes = weekly_sales.refreshes + 1""" + db.execute("""INSERT INTO weekly_sales VALUES (%s, %s, %s, %s) + ON CONFLICT (week) """ + conflict, + (week, now, 0 if initialize else 1, Jsonb(products))) + + +def latest(): + with connect() as db: + row = db.execute("SELECT * FROM weekly_sales ORDER BY week DESC LIMIT 1").fetchone() + items = row["products"] + return dict(week=row["week"].isoformat(), refreshed_at=row["refreshed_at"].isoformat(), + refreshes=row["refreshes"], products=items, units=sum(it["units"] for it in items), + revenue=str(sum(Decimal(it["revenue"]) for it in items))) + + +@web.get("/") +def dashboard(): + return render_template("report.html", report=latest()) + + +@web.get("/api/report") +def report_json(): + return jsonify(latest()) + + +if __name__ == "__main__": + if sys.argv[1:] not in (["initialize"], ["refresh"]): + raise SystemExit("Usage: python report.py initialize|refresh") + refresh(initialize=sys.argv[1] == "initialize") diff --git a/python/langchain-floo/examples/weekly-sales/app/requirements.txt b/python/langchain-floo/examples/weekly-sales/app/requirements.txt new file mode 100644 index 0000000..ece3e7a --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/app/requirements.txt @@ -0,0 +1,3 @@ +Flask>=3.1,<4 +gunicorn>=23,<28 +psycopg[binary]>=3.2,<4 diff --git a/python/langchain-floo/examples/weekly-sales/app/sales.csv b/python/langchain-floo/examples/weekly-sales/app/sales.csv new file mode 100644 index 0000000..b4a0bda --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/app/sales.csv @@ -0,0 +1,6 @@ +Date,Product,Units Sold,Revenue +2025-08-01,Widget A,10,250 +2025-08-02,Widget B,5,125 +2025-08-03,Widget A,7,175 +2025-08-04,Widget C,3,90 +2025-08-05,Widget B,8,200 diff --git a/python/langchain-floo/examples/weekly-sales/deploy.py b/python/langchain-floo/examples/weekly-sales/deploy.py new file mode 100644 index 0000000..4bdb501 --- /dev/null +++ b/python/langchain-floo/examples/weekly-sales/deploy.py @@ -0,0 +1,56 @@ +"""Deploy the sample dashboard with the same tools available to a LangChain agent.""" +import argparse +import asyncio +import json +import os +from pathlib import Path + +from langchain_floo import load_floo_tools + + +async def deploy(app_name): + org = os.environ["FLOO_ORG_ID"] + names = ["plan_deploy", "create_app", "list_files", "write_files", "get_app_status"] + tools = {tool.name: tool for tool in await load_floo_tools(tool_names=names)} + + async def call(name, **arguments): + blocks = await tools[name].ainvoke({"org_id": org, **arguments}) + return json.loads(blocks[0]["text"]) + + plan = await call("plan_deploy", body={"app": app_name, "source": "floo", "access_mode": "public"}) + if plan.get("decision") != "create_hosted": + raise SystemExit(f"Choose an unused app name. {plan['message']}") + + app = await call("create_app", body={"name": app_name, "access_mode": "public", + "source": {"kind": "floo", "starter": True}}) + app_id = app["id"] + print(f"Created {app_name} ({app_id})", flush=True) + tree = await call("list_files", app_id=app_id) + files = [] + directory = Path(__file__).parent / "app" + for filename in ("Dockerfile", "floo.app.toml", "report.html", "report.py", "requirements.txt", "sales.csv"): + path = directory / filename + content = path.read_text(encoding="utf-8") + if path.name == "floo.app.toml": + content = content.replace('name = "langchain-sales-report"', f'name = "{app_name}"') + files.append({"path": path.name, "content": content}) + commit = await call("write_files", app_id=app_id, body={ + "files": files, "message": "Deploy weekly sales dashboard", "base_sha": tree["commit_sha"], + }) + sha = commit["commit_sha"] + print(f"Waiting for {sha} on dev", flush=True) + for _ in range(120): + status = await call("get_app_status", app_id=app_id, commit=sha) + if status["live"]: + print(next(e["url"] for e in app["envs"] if e["name"] == "dev")) + return + if (status.get("deploy") or {}).get("status") in {"failed", "cancelled", "canceled"}: + raise SystemExit(f"{status['summary']} {status.get('next_step') or ''}") + await asyncio.sleep(5) + raise SystemExit(f"Deploy still pending. Inspect {app_name} in the floo dashboard.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("app", help="An unused floo app name") + asyncio.run(deploy(parser.parse_args().app))