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
86 changes: 78 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,80 @@
# nl-postgres

[Vercel's Natural Language Postgres](https://github.com/vercel-labs/natural-language-postgres) on
**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage
and prod on every merge, and then packaged as an Orun baseline.

This commit is the repository's frame: `intent.yaml` (with the placeholder
workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun
CI workflow, the shared TypeScript and ESLint configuration, and the spec
index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md).
Vercel's [Natural Language Postgres](https://github.com/vercel-labs/natural-language-postgres)
— a question about a table of unicorn companies asked in plain English, the
SQL a model writes for it, the rows, a chart of them and an explanation of
the query: one page and four server actions — running on **Cloudflare
Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare),
its SQL written by **Workers AI** through the Worker's `AI` binding and run
as a **read-only database role**, its table a **Supabase** project's
database reached through **Cloudflare Hyperdrive**, both provisioned by
Terraform through [Orun](https://github.com/sourceplane/orun) and the schema
applied by Orun's `db-migrate`, the way the
[rag-chatbot baseline](https://github.com/sourceplane/rag-chatbot) does it, deployed by
[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge.
Packaging it as an Orun baseline is the next milestone (NL2).

The template's code is the code. What the port changes is what the Workers
runtime, a fresh unattended deployment and SQL written by a model force: the
database client is built per call over the Hyperdrive binding (`lib/db.ts`);
the model is Workers AI's (`lib/ai/models.ts`) — the platform brokers no AI
vendor, and the Cloudflare account the app deploys into already is one —
with upstream's OpenAI model behind an optional key; and the model's SQL runs
only as `query_reader`, a role that can read the one table and nothing else,
through a function it cannot step out of (migration `040_read_only_queries`),
with the template's own string check kept in front. The template's data is
CB Insights' list, which each owner downloads; a fresh product starts with
sixty fictional companies in its shape, and a tool turns the owner's CSV into
a migration. See [`specs/epics/nl-postgres`](specs/epics/nl-postgres/README.md)
for the design, the milestones and the as-built status, including every
departure.

## What is here (the product)

| Surface | Where |
|---|---|
| The product's name and source link | `apps/web/lib/site.ts` |
| The page and its four server actions, `/api/health` | `apps/web/app` |
| The model: Workers AI, or OpenAI behind an optional key | `apps/web/lib/ai/models.ts` |
| The per-call client and the read-only query path | `apps/web/lib/db.ts` |
| Workers build and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` |
| The table, the sample data, row-level security and the read-only role as migrations, and Lumen's runner | `packages/db` (`@saas/db`) |
| CB Insights' CSV as a migration; the local apply | `tooling/migrations` |
| The Supabase project, the Hyperdrive config, the migration step | `infra/terraform/supabase`, `infra/terraform/cloudflare-hyperdrive`, `infra/db-migrate` |
| Tests | `tests/web`, `tests/db` (vitest) |

## Getting started

```bash
pnpm install
pnpm run wire:fixture # re-render apps/web/wrangler.jsonc from its template (committed; this changes nothing)
pnpm typecheck
pnpm lint
pnpm test
pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next
pnpm --filter @saas/db run manifest:check
```

The build needs no database, no model and no Cloudflare credential. Running
it locally — a Postgres on `localhost:5432`, `pnpm --filter @app/web
db:migrate:local`, `wrangler login` for Workers AI, `next dev` or `wrangler
dev` — is in the product's README (`.baseline/product/README.md`), which is
what a product built from here carries.

## How it maps to Vercel

| Vercel | Here |
|---|---|
| Next.js 15.5 hosting, four server actions | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets on Next.js 16.3.8 (the adapter refuses 15.5); the actions run as they did |
| `"openai/gpt-5.4-mini"` through Vercel's AI Gateway | Workers AI through the `AI` binding: `@cf/meta/llama-4-scout-17b-16e-instruct`, in JSON mode for the three structured outputs, no key. `OPENAI_API_KEY`, if set, switches to upstream's `gpt-5.4-mini` straight from OpenAI |
| `sql.query(query)` from `@vercel/postgres`, on the owner's connection | `runReadOnlyQuery()`: the query through `app_private.run_read_only` as `query_reader`, in a read-only transaction with a 5 s timeout, behind the template's own check |
| Vercel Postgres | The Supabase project's Postgres through a Hyperdrive config; `getSql()` builds the `postgres` client per call from the `HYPERDRIVE` binding's connection string |
| `pnpm run seed` (lib/seed.ts: the table, and CB Insights' CSV) | `packages/db` + `infra/db-migrate`: the same CREATE TABLE, sixty fictional sample companies, row-level security and the read-only role, applied through Supabase's Management API before the Worker deploys; `tooling/migrations/csv-to-sql.mjs` turns the CSV into a migration |
| A Postgres database created in the dashboard | `infra/terraform/supabase` (one project per environment) + `infra/terraform/cloudflare-hyperdrive` (one config per environment), ids and credentials as orun secrets |
| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, provisioned, deployed; the header links to its own source |

## CI

| Workflow | What it runs | Ships to a product |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow a product carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the app built and dry-deployed per environment, both Terraform roots checked and planned, the migrations planned); no lane runs the `typecheck`, `lint` or `test` scripts — `baseline.yml`'s e2e tier runs them on the bootstrapped product before every tag, and a product's developers run them before they push. The bootstrap's own landings (`orun/BASE-*`) run `plan` alone and nothing waits for it — the landing was checked in the build box; a merge applies, migrates and deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes |
11 changes: 11 additions & 0 deletions apps/web/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`.
# Copy to .dev.vars (git-ignored). Every key is optional: the database is not
# here (the Worker reaches it through the HYPERDRIVE binding, wrangler.jsonc),
# and neither is the model — Workers AI answers through the AI binding.
#
# OpenAI instead of Workers AI: set, the SQL is written, explained and charted
# by upstream's own model, gpt-5.4-mini, straight from OpenAI. In stage/prod
# this is a Worker secret the owner sets once per environment:
# `wrangler secret put OPENAI_API_KEY --name nl-postgres-web-<env>`
# (README, "Use OpenAI instead").
# OPENAI_API_KEY=
17 changes: 17 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Local development. Copy to .env.local (git-ignored); never commit a value.
#
# DATABASE_URL is read by `pnpm --filter @app/web db:migrate:local` (which
# applies packages/db's migrations to a local Postgres) and by the app only
# when no Cloudflare context is available. Under `next dev` and `wrangler dev`
# the app reads the HYPERDRIVE binding from wrangler.jsonc instead (its
# localConnectionString — point both at the same database).
DATABASE_URL=postgres://postgres:postgres@localhost:5432/unicorns
# Optional. Unset, the SQL is written by Workers AI, through the AI binding
# (`next dev` reaches it after `wrangler login`). Set, it is written by
# upstream's own model, OpenAI's gpt-5.4-mini, straight from OpenAI; `next
# dev` reads it from here, `wrangler dev` from .dev.vars.
# OPENAI_API_KEY=
# Optional: the site's public origin, which the page's Open Graph image link
# is resolved against. The Orun build sets it per environment
# (component.yaml); unset, it is http://localhost:3000.
NEXT_PUBLIC_SITE_URL=http://localhost:3000
4 changes: 4 additions & 0 deletions apps/web/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"typescript.tsdk": "node_modules/.pnpm/typescript@5.0.4/node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
13 changes: 13 additions & 0 deletions apps/web/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2024 Vercel, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
115 changes: 115 additions & 0 deletions apps/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Natural Language PostgreSQL


[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres&env=OPENAI_API_KEY&envDescription=Learn%20more%20about%20how%20to%20get%20the%20API%20Keys%20for%20the%20application&envLink=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres%2Fblob%2Fmain%2F.env.example&demo-title=Natural%20Language%20Postgres&demo-description=Query%20PostgreSQL%20database%20using%20natural%20language%20and%20visualize%20results%20with%20Next.js%20and%20AI%20SDK.&demo-url=https%3A%2F%2Fnatural-language-postgres.vercel.app&stores=%5B%7B%22type%22%3A%22postgres%22%7D%5D)

This project is a Next.js application that allows users to query a PostgreSQL database using natural language and visualize the results. It's powered by the AI SDK by Vercel and uses OpenAI's GPT-4o model to translate natural language queries into SQL.

## Features

- Natural Language to SQL: Users can input queries in plain English, which are then converted to SQL using AI.
- Data Visualization: Results are displayed in both table and chart formats, with the chart type automatically selected based on the data.
- Query Explanation: Users can view the full SQL query and get an AI-generated explanation of each part of the query.

## Technology Stack

- Next.js for the frontend and API routes
- AI SDK by Vercel for AI integration
- OpenAI's GPT-4o for natural language processing
- PostgreSQL for data storage
- Vercel Postgres for database hosting
- Framer Motion for animations
- ShadowUI for UI components
- Tailwind CSS for styling
- Recharts for data visualization

## How It Works

1. The user enters a natural language query about unicorn companies.
2. The application uses GPT-4 to generate an appropriate SQL query.
3. The SQL query is executed against the PostgreSQL database.
4. Results are displayed in a table format.
5. An AI-generated chart configuration is created based on the data.
6. The results are visualized using the generated chart configuration.
7. Users can toggle between table and chart views.
8. Users can request an explanation of the SQL query, which is also generated by AI.

## Data

The database contains information about unicorn companies, including:

- Company name
- Valuation
- Date joined (unicorn status)
- Country
- City
- Industry
- Select investors

This data is based on CB Insights' list of unicorn companies.

## Getting Started

To get the project up and running, follow these steps:

1. Install dependencies:

```bash
pnpm install
```

2. Copy the example environment file:

```bash
cp .env.example .env
```

3. Add your OpenAI API key and PostgreSQL connection string to the `.env` file:

```
OPENAI_API_KEY=your_api_key_here
POSTGRES_URL="..."
POSTGRES_PRISMA_URL="..."
POSTGRES_URL_NO_SSL="..."
POSTGRES_URL_NON_POOLING="..."
POSTGRES_USER="..."
POSTGRES_HOST="..."
POSTGRES_PASSWORD="..."
POSTGRES_DATABASE="..."
```
4. Download the dataset:
- Go to https://www.cbinsights.com/research-unicorn-companies
- Download the unicorn companies dataset
- Save the file as `unicorns.csv` in the root of your project

5. Seed the database:
```bash
pnpm run seed
```

6. Start the development server:
```bash
pnpm run dev
```

Your project should now be running on [http://localhost:3000](http://localhost:3000).

## Deployment

The project is set up for easy deployment on Vercel. Use the "Deploy with Vercel" button in the repository to create your own instance of the application.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres&env=OPENAI_API_KEY&envDescription=Learn%20more%20about%20how%20to%20get%20the%20API%20Keys%20for%20the%20application&envLink=https%3A%2F%2Fgithub.com%2Fvercel-labs%2Fnatural-language-postgres%2Fblob%2Fmain%2F.env.example&demo-title=Natural%20Language%20Postgres&demo-description=Query%20PostgreSQL%20database%20using%20natural%20language%20and%20visualize%20results%20with%20Next.js%20and%20AI%20SDK.&demo-url=https%3A%2F%2Fnatural-language-postgres.vercel.app&stores=%5B%7B%22type%22%3A%22postgres%22%7D%5D)


## Learn More

To learn more about the technologies used in this project, check out the following resources:

- [Next.js Documentation](https://nextjs.org/docs)
- [AI SDK](https://sdk.vercel.ai/docs)
- [OpenAI](https://openai.com/)
- [Vercel Postgres powered by Neon](https://vercel.com/docs/storage/vercel-postgres)
- [Framer Motion](https://www.framer.com/motion/)
- [ShadcnUI](https://ui.shadcn.com/)
- [Tailwind CSS](https://tailwindcss.com/docs)
- [Recharts](https://recharts.org/en-US/)
Loading
Loading