Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions .github/workflows/langchain-floo.yml
Original file line number Diff line number Diff line change
@@ -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
14 changes: 13 additions & 1 deletion python/langchain-floo/README.md
Original file line number Diff line number Diff line change
@@ -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:

Expand All @@ -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)
6 changes: 6 additions & 0 deletions python/langchain-floo/examples/weekly-sales/app/Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
19 changes: 19 additions & 0 deletions python/langchain-floo/examples/weekly-sales/app/floo.app.toml
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions python/langchain-floo/examples/weekly-sales/app/report.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Weekly sales report</title>
<style>
*{box-sizing:border-box}body{background:#f6f2eb;color:#261f18;font:1rem/1.5 system-ui,sans-serif;margin:0}main{max-width:50rem;margin:10vh auto;padding:0 6%}h1{font:clamp(2.8rem,8vw,5.2rem)/1.05 Georgia,serif;margin:0}p{color:#665f56}dl{display:flex;gap:4rem;margin:2.8rem 0}dt{color:#665f56}dd{margin:0;color:#954314;font:3.2rem/1.2 Georgia,serif}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{text-align:right;padding:.75rem 0;border-bottom:1px solid #cbc4b8}td:first-child,th:first-child{text-align:left}footer{color:#665f56;margin:2rem 0;font-size:.85rem}a{color:#764119}
</style>
<main><h1>Weekly sales report</h1><p>Sample sales data · Snapshot for the week of {{ report.week }}</p>
<dl><div><dt>Units sold</dt><dd>{{ report.units }}</dd></div><div><dt>Revenue</dt><dd>{{ report.revenue }}</dd></div></dl>
<table><thead><tr><th>Product</th><th>Units</th><th>Revenue</th></tr></thead><tbody>
{% for product in report.products %}<tr><td>{{ product.name }}</td><td>{{ product.units }}</td><td>{{ product.revenue }}</td></tr>{% endfor %}
</tbody></table><footer>Last refreshed {{ report.refreshed_at }} · <a href="/api/report">View JSON</a></footer></main></html>
72 changes: 72 additions & 0 deletions python/langchain-floo/examples/weekly-sales/app/report.py
Original file line number Diff line number Diff line change
@@ -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")
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Flask>=3.1,<4
gunicorn>=23,<28
psycopg[binary]>=3.2,<4
6 changes: 6 additions & 0 deletions python/langchain-floo/examples/weekly-sales/app/sales.csv
Original file line number Diff line number Diff line change
@@ -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
56 changes: 56 additions & 0 deletions python/langchain-floo/examples/weekly-sales/deploy.py
Original file line number Diff line number Diff line change
@@ -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))