diff --git a/README.md b/README.md index 93797f8..80bb895 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,87 @@ # doc-search -[Supabase's Next.js OpenAI Doc Search Starter](https://github.com/supabase-community/nextjs-openai-doc-search) 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). +Supabase's [Next.js OpenAI Doc Search Starter](https://github.com/supabase-community/nextjs-openai-doc-search) +— a ⌘K dialog that answers a question about your docs: the MDX pages under +`pages/docs` split into sections by heading, each section embedded and +stored in Postgres with pgvector, the question embedded and matched against +them, and an answer streamed from the closest sections — running on +**Cloudflare Workers + Static Assets** through [`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), +embedding and answering with **Workers AI** through the Worker's `AI` +binding, its index 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 (DQ2). + +The template's code is the code. What the port changes is what the Workers +runtime and a fresh, unattended deployment force: the database is reached +with SQL over the Hyperdrive binding (`lib/db/index.ts`) instead of through +Supabase's Data API with a service-role key; the models are 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 for the answers; and the docs are embedded by the +deployed Worker, not by the build. Upstream's `pnpm build` embedded every +changed page with OpenAI and wrote it through the Data API, with both keys +in the build; here the build only splits the docs into sections +(`lib/docs/index.generated.json`), and the deploy's smoke step POSTs +`/api/embeddings`, where the Worker embeds the pages whose checksum the +database does not hold through its own AI binding. The column and the search +function are sized to Workers AI's embedding model (768 dimensions, migration +`020_workers_ai_embeddings`). See [`specs/epics/doc-search`](specs/epics/doc-search/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 search dialog | `apps/web/pages/index.tsx`, `apps/web/components/SearchDialog.tsx` | +| The docs the search answers from | `apps/web/pages/docs/**/*.mdx` | +| The search, the indexing, `/api/health` | `apps/web/app/api/{vector-search,embeddings,health}/route.ts` | +| The models: Workers AI, or OpenAI for the answers behind an optional key | `apps/web/lib/ai/models.ts` | +| The docs index (built) and the sync into Postgres (run by the Worker) | `apps/web/scripts/build-docs-index.ts` → `lib/docs/index.generated.json`, `lib/docs/process-mdx.ts`, `lib/docs/sync.ts` | +| The per-call database client | `apps/web/lib/db/index.ts` (`getSql()`) | +| Workers build and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` → `wrangler.jsonc` (committed), `component.yaml` | +| The schema as migrations, and Lumen's runner | `packages/db` (`@saas/db`) | +| 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 # the docs index + 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 with pgvector on `localhost:5432` with the +migrations applied, `wrangler login` for Workers AI, `next dev` or `wrangler +dev`, then `POST /api/embeddings` to index the docs — 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 hosting (an edge-runtime API route streams the answer) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets; the page stays on the Pages Router and the route is an App Router route handler (an edge-runtime route does not run under OpenNext), streaming plain text as it did | +| OpenAI for everything, `OPENAI_KEY` required: `text-embedding-ada-002` (1536 dimensions), `gpt-3.5-turbo`, the moderation endpoint | Workers AI through the `AI` binding: `@cf/baai/bge-base-en-v1.5` (768 dimensions) for the docs and the question, `@cf/meta/llama-4-scout-17b-16e-instruct` for the answer, no key. `OPENAI_API_KEY`, if set, switches the answer — not the embeddings — to upstream's OpenAI model, straight from OpenAI, with upstream's moderation step first. No AI gateway | +| Supabase's Data API with `NEXT_PUBLIC_SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` | The Supabase project's Postgres through a Hyperdrive config, with SQL; no service-role key exists, and the Data API is shut out of both tables (upstream's row-level security) and both functions (migration `030`) | +| `pnpm run embeddings && next build`: the build embeds every changed page and upserts it | The build splits the docs (`lib/docs/index.generated.json`, no credential); the deploy's smoke POSTs `/api/embeddings` and the Worker embeds the changed pages and writes them, checksum by checksum as upstream did | +| `supabase/migrations` applied with the Supabase CLI | `packages/db` + `infra/db-migrate`: upstream's migration verbatim, then the resize to 768 dimensions with a cosine `match_page_sections()`, applied through Supabase's Management API after the project and the Hyperdrive config exist, before the Worker deploys | +| A Supabase project 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, indexed | + +## 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 | diff --git a/apps/web/.dev.vars.example b/apps/web/.dev.vars.example new file mode 100644 index 0000000..ce730d3 --- /dev/null +++ b/apps/web/.dev.vars.example @@ -0,0 +1,19 @@ +# 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 embeds and answers through the AI +# binding. +# +# OpenAI for the ANSWERS only (embeddings stay on Workers AI: the column is +# sized to its model, and the docs and a question must share one). Set, the +# answer is upstream's OpenAI model, straight from OpenAI, and the question +# goes through OpenAI's moderation endpoint first, as upstream did. In +# stage/prod this is a Worker secret the owner sets once per environment: +# `wrangler secret put OPENAI_API_KEY --name doc-search-web-` +# (README, "Use OpenAI for the answers"). +# OPENAI_API_KEY= +# OPENAI_MODEL=gpt-3.5-turbo +# +# How similar a section must be to the question to reach the answer, as +# cosine similarity (lib/search.ts, default 0.6). +# MATCH_THRESHOLD=0.6 diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..d451c96 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,13 @@ +# Local development. Copy to .env.local (git-ignored); never commit a value. +# +# DATABASE_URL is read only when no Cloudflare context is available (a +# script). Under `next dev` and `wrangler dev` the app reads the HYPERDRIVE +# binding from wrangler.jsonc instead (its localConnectionString — point both +# at the same database). The database needs the `vector` extension available +# and packages/db's migrations applied (README → Local development). +DATABASE_URL=postgres://postgres:postgres@localhost:5432/docs +# Optional. Unset, the embeddings and the answers are Workers AI's, through +# the AI binding (`next dev` reaches it after `wrangler login`). Set, the +# ANSWERS are OpenAI's; `next dev` reads it from here, `wrangler dev` from +# .dev.vars. +# OPENAI_API_KEY= diff --git a/apps/web/LICENSE b/apps/web/LICENSE new file mode 100644 index 0000000..e029233 --- /dev/null +++ b/apps/web/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Supabase + + 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. diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..b885a45 --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,42 @@ +# apps/web — the app + +A documentation search from Supabase's +[Next.js OpenAI Doc Search Starter](https://github.com/supabase-community/nextjs-openai-doc-search) +(Apache-2.0, see `LICENSE`), running on Cloudflare Workers + Static Assets. +Vercel lists it at https://vercel.com/templates/next.js/nextjs-openai-doc-search-starter. + +- The page (`/`, `pages/index.tsx`): upstream's, a ⌘K search dialog + (`components/SearchDialog.tsx`) that streams an answer to a question about + the docs. The title reads `SITE_NAME` (`lib/site.ts`). +- The docs: `pages/docs/**/*.mdx`. They are not pages (Next.js renders no + MDX here, as upstream): they are what the search answers from. +- The search (`POST /api/vector-search`, `app/api/vector-search/route.ts`): + upstream's steps — moderate, embed the question, match page sections, build + a 1500-token context, stream the answer — with upstream's prompt. +- The indexing (`POST /api/embeddings`, `app/api/embeddings/route.ts`): + upstream's build-time `pnpm run embeddings`, moved into the Worker. The + build splits the docs into sections (`scripts/build-docs-index.ts` → + `lib/docs/index.generated.json`, with upstream's MDX processing in + `lib/docs/process-mdx.ts`); the deploy's smoke step POSTs here, and the + Worker embeds every page whose checksum the database does not hold + (`lib/docs/sync.ts`). +- `/api/health`: 200 only when the database is reachable through Hyperdrive + and migrated; it says how much of the docs is indexed and calls no model. + +The models are Workers AI's through the Worker's `AI` binding +(`lib/ai/models.ts`): `@cf/baai/bge-base-en-v1.5` for the embeddings (768 +dimensions, the column's size) and `@cf/meta/llama-4-scout-17b-16e-instruct` +for the answers. `OPENAI_API_KEY` (a Worker secret) switches the answers to +OpenAI's model, straight from OpenAI, with upstream's moderation step first; +the embeddings stay on Workers AI. + +The database is a Supabase project's Postgres with pgvector, reached through +the `HYPERDRIVE` binding (`lib/db/index.ts`); its schema is +`packages/db`'s migrations, which `infra/db-migrate` applies before every +deploy. + +```bash +pnpm --filter @app/web docs:index # re-split pages/docs into lib/docs/index.generated.json +pnpm --filter @app/web build # docs index + next build + opennextjs-cloudflare build +pnpm --filter @app/web preview # wrangler dev over the built Worker +``` diff --git a/apps/web/app/api/embeddings/route.ts b/apps/web/app/api/embeddings/route.ts new file mode 100644 index 0000000..141123e --- /dev/null +++ b/apps/web/app/api/embeddings/route.ts @@ -0,0 +1,47 @@ +import index from '@/lib/docs/index.generated.json' +import type { DocsIndex } from '@/lib/docs/index-types' +import { syncDocs } from '@/lib/docs/sync' +import { DatabaseNotConfiguredError, getSql } from '@/lib/db' +import { AiNotConfiguredError, embeddingModel } from '@/lib/ai/models' + +// Not upstream's route — upstream's step, moved. Upstream embedded the docs +// at `pnpm build` (`pnpm run embeddings`), with OpenAI's key and Supabase's +// service-role key in the build's environment. Here the build only writes the +// docs index (scripts/build-docs-index.ts, bundled into this Worker), and +// this route embeds it: Workers AI through the Worker's own AI binding, +// written to Postgres through its HYPERDRIVE binding. The deploy's smoke step +// POSTs here right after `wrangler deploy` (apps/web/component.yaml), so every +// deploy leaves the database holding its own docs — the brief's "embeddings in +// CI", with no credential in CI or in the build. +// +// It takes no input. What it embeds is the docs this Worker was built with, +// and only the pages whose checksum the database does not already hold, so +// calling it again — by the next deploy, a retry, or anybody — does one SELECT +// per page and embeds nothing. `?refresh=1` is upstream's `--refresh`: embed +// every page again, which only a change of embedding model calls for. +export const dynamic = 'force-dynamic' + +export async function POST(req: Request) { + const refresh = new URL(req.url).searchParams.get('refresh') === '1' + let sql: Awaited> | undefined + try { + sql = await getSql() + const result = await syncDocs(sql, await embeddingModel(), index as DocsIndex, { refresh }) + const ok = result.failed.length === 0 + return Response.json( + { ok, ...result }, + { status: ok ? 200 : 500, headers: { 'cache-control': 'no-store' } } + ) + } catch (error) { + if (error instanceof AiNotConfiguredError || error instanceof DatabaseNotConfiguredError) { + return Response.json({ ok: false, error: error.message }, { status: 503 }) + } + console.error('embeddings: sync failed', error) + return Response.json( + { ok: false, error: 'The docs could not be indexed' }, + { status: 500, headers: { 'cache-control': 'no-store' } } + ) + } finally { + await sql?.end({ timeout: 5 }).catch(() => {}) + } +} diff --git a/apps/web/app/api/health/route.ts b/apps/web/app/api/health/route.ts new file mode 100644 index 0000000..732442e --- /dev/null +++ b/apps/web/app/api/health/route.ts @@ -0,0 +1,54 @@ +import { getSql } from '@/lib/db' +import { EMBEDDING_DIMENSIONS, chatProvider } from '@/lib/ai/models' + +// Not upstream's: the deploy's smoke check and the bootstrap's probe read +// this. The page renders without the database, so this proves what it never +// touches until somebody searches — the HYPERDRIVE binding names a real +// config, Hyperdrive reaches the Supabase database, and db-migrate applied the +// schema: both tables, and the embedding column at the size of the model the +// app embeds with (020_workers_ai_embeddings). It reports how much of the docs +// is indexed (`pages`, `sections`) and which provider writes the answers. It +// calls no model. +export const dynamic = 'force-dynamic' + +export async function GET() { + let sql: Awaited> | undefined + try { + sql = await getSql() + const [row] = await sql< + { pages: string | null; sections: string | null; dimensions: number | null }[] + >`select to_regclass('public.nods_page')::text as pages, + to_regclass('public.nods_page_section')::text as sections, + (select a.atttypmod from pg_attribute a + where a.attrelid = to_regclass('public.nods_page_section') + and a.attname = 'embedding') as dimensions` + const migrated = Boolean( + row?.pages && row?.sections && Number(row?.dimensions) === EMBEDDING_DIMENSIONS + ) + let indexed = { pages: 0, sections: 0 } + if (migrated) { + const [counts] = await sql<{ pages: number; sections: number }[]>` + select (select count(*)::int from nods_page where checksum is not null) as pages, + (select count(*)::int from nods_page_section) as sections` + indexed = counts! + } + return Response.json( + { + ok: migrated, + database: 'reachable', + schema: migrated ? 'migrated' : 'missing', + ...indexed, + answers: await chatProvider(), + }, + { status: migrated ? 200 : 503, headers: { 'cache-control': 'no-store' } } + ) + } catch (error) { + console.error('health: database check failed', error) + return Response.json( + { ok: false, database: 'unreachable' }, + { status: 503, headers: { 'cache-control': 'no-store' } } + ) + } finally { + await sql?.end({ timeout: 5 }).catch(() => {}) + } +} diff --git a/apps/web/app/api/vector-search/route.ts b/apps/web/app/api/vector-search/route.ts new file mode 100644 index 0000000..00c0506 --- /dev/null +++ b/apps/web/app/api/vector-search/route.ts @@ -0,0 +1,143 @@ +import { codeBlock, oneLine } from 'common-tags' +import { embed, streamText } from 'ai' +import { ApplicationError, UserError } from '@/lib/errors' +import { DatabaseNotConfiguredError, getSql } from '@/lib/db' +import { AiNotConfiguredError, chatModel, embeddingModel, moderate } from '@/lib/ai/models' +import { + contextFrom, + EMPTY_INDEX_ANSWER, + MATCH_COUNT, + matchThreshold, + MIN_CONTENT_LENGTH, + type MatchedSection, +} from '@/lib/search' + +// Upstream's pages/api/vector-search.ts, as an App Router route handler: the +// same request ({ prompt }), the same steps — moderate, embed the question, +// match page sections, build the context, stream the answer — and the same +// prompt, word for word. What changed is where each step runs: the question +// is embedded by Workers AI (lib/ai/models.ts), the sections are matched by +// SQL over Hyperdrive instead of an RPC through Supabase's Data API, and the +// answer is Workers AI's, or OpenAI's when OPENAI_API_KEY is set (then, and +// only then, moderated first, as upstream did). Upstream's `runtime = 'edge'` +// is gone: OpenNext runs every route in the Worker, and an edge-runtime route +// does not run there. +export const dynamic = 'force-dynamic' + +export async function POST(req: Request) { + try { + const requestData = (await req.json().catch(() => null)) as { prompt?: unknown } | null + + if (!requestData) { + throw new UserError('Missing request data') + } + + const { prompt: query } = requestData + + if (!query) { + throw new UserError('Missing query in request data') + } + + const sanitizedQuery = String(query).trim() + + // Moderate the content to comply with OpenAI T&C — when the answer is + // OpenAI's (moderate() returns null on Workers AI). + const flagged = await moderate(sanitizedQuery) + if (flagged) { + throw new UserError('Flagged content', { + flagged: true, + categories: flagged, + }) + } + + const sql = await getSql() + try { + const [{ sections }] = await sql<{ sections: number }[]>` + select count(*)::int as sections from nods_page_section` + if (sections === 0) { + return new Response(EMPTY_INDEX_ANSWER, { + headers: { 'content-type': 'text/plain; charset=utf-8' }, + }) + } + + // Create embedding from query + const { embedding } = await embed({ + model: await embeddingModel(), + value: sanitizedQuery.replaceAll('\n', ' '), + }) + + const pageSections = await sql` + select content, token_count, similarity + from match_page_sections(${'[' + embedding.join(',') + ']'}::vector, + ${await matchThreshold()}, ${MATCH_COUNT}, ${MIN_CONTENT_LENGTH})` + + const contextText = contextFrom(pageSections) + + const prompt = codeBlock` + ${oneLine` + You are a very enthusiastic Supabase representative who loves + to help people! Given the following sections from the Supabase + documentation, answer the question using only that information, + outputted in markdown format. If you are unsure and the answer + is not explicitly written in the documentation, say + "Sorry, I don't know how to help with that." + `} + + Context sections: + ${contextText} + + Question: """ + ${sanitizedQuery} + """ + + Answer as markdown (including related code snippets if available): + ` + + const result = streamText({ + model: await chatModel(), + prompt, + maxOutputTokens: 512, + temperature: 0, + }) + + return result.toTextStreamResponse() + } finally { + // The stream reads nothing more from the database once it has started. + await sql.end({ timeout: 5 }).catch(() => {}) + } + } catch (err: unknown) { + if (err instanceof UserError) { + return new Response( + JSON.stringify({ + error: err.message, + data: err.data, + }), + { + status: 400, + headers: { 'Content-Type': 'application/json' }, + } + ) + } else if (err instanceof AiNotConfiguredError || err instanceof DatabaseNotConfiguredError) { + // Not upstream's: a Worker without its bindings (a `next dev` with no + // platform proxy) says so instead of answering a bare 500. + return Response.json({ error: err.message }, { status: 503 }) + } else if (err instanceof ApplicationError) { + // Print out application errors with their additional data + console.error(`${err.message}: ${JSON.stringify(err.data)}`) + } else { + // Print out unexpected errors as is to help with debugging + console.error(err) + } + + // TODO: include more response info in debug environments + return new Response( + JSON.stringify({ + error: 'There was an error processing your request', + }), + { + status: 500, + headers: { 'Content-Type': 'application/json' }, + } + ) + } +} diff --git a/apps/web/cloudflare-env.d.ts b/apps/web/cloudflare-env.d.ts new file mode 100644 index 0000000..040f0cb --- /dev/null +++ b/apps/web/cloudflare-env.d.ts @@ -0,0 +1,17 @@ +// The bindings wrangler.template.jsonc gives the Worker, as seen through +// `getCloudflareContext().env` from @opennextjs/cloudflare (which types `env` +// as the global `CloudflareEnv` interface for the app to augment). Regenerate +// with `wrangler types --env-interface CloudflareEnv` after changing the +// bindings. +/// +interface CloudflareEnv { + HYPERDRIVE: Hyperdrive; + AI: Ai; + ASSETS: Fetcher; + // Optional Worker secret (lib/ai/models.ts): upstream's OpenAI answer model. + OPENAI_API_KEY?: string; + // Optional Worker vars: which OpenAI chat model (default upstream's), and + // how similar a section must be to reach the answer (lib/search.ts). + OPENAI_MODEL?: string; + MATCH_THRESHOLD?: string; +} diff --git a/apps/web/component.yaml b/apps/web/component.yaml new file mode 100644 index 0000000..b63fceb --- /dev/null +++ b/apps/web/component.yaml @@ -0,0 +1,127 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: web + description: Vercel's Next.js OpenAI Doc Search Starter (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, Workers AI for embeddings and answers, the docs indexed into Supabase pgvector on every deploy, per environment) +spec: + type: cloudflare-workers-assets-turbo + lifecycle: production + owner: platform + # Its pages, attached to it in the workspace's catalog: what the Docs + # library shows for it, and what the catalog's docs and runbook checks read. + # Generated from what this manifest and its sources declare. + docs: + overview: docs/overview.md + pages: + - { path: docs/architecture.md, role: architecture, title: Architecture } + - { path: docs/runbook.md, role: runbook, title: Runbook } + # `app`, not `web`: a domain and a component share one name space in the + # catalog, and a domain called `web` hid this component from it. + domain: app + path: apps/web + # Its own lane per environment: the Next.js build is the longest job in the + # plan, and a shared lane would wait on it. + lane: isolated + # INFRA BEFORE APP, ENFORCED ON MAIN. A merge to main converges the whole + # product in one run: the Supabase project, then the Hyperdrive config over + # its database, then the migrations — upstream's pages and sections with + # the vector extension and row-level security, the embeddings at Workers + # AI's 768 dimensions, the functions closed to the Data API — then this + # Worker. Its deploy reads the Hyperdrive id + # (WIRING_CLOUDFLARE_HYPERDRIVE_, rendered into the HYPERDRIVE binding) + # and needs the schema applied, and a job resolves its secrets when it + # STARTS — so it waits on both, `mode: enforced`, and the ids the applies + # lease-published are there. A pull request deploys nothing, so nothing on + # one waits: every edge is advisory there. + dependsOn: + - component: cloudflare-hyperdrive + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + - component: db-migrate + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The wiring documents the cloudflare-hyperdrive root lease-publishes, one + # per deployed environment; tooling/wire/live.mjs picks this job's. Workers + # AI needs nothing here: the AI binding is the account the deploy targets. + # OPENAI_API_KEY, if an owner wants OpenAI's model for the answers, is a + # Worker secret they set once per environment (README); the lane never sets + # it. + secretEnv: + WIRING_CLOUDFLARE_HYPERDRIVE_STAGE: "secret://doc-search/doc-search/stage/WIRING_CLOUDFLARE_HYPERDRIVE" + WIRING_CLOUDFLARE_HYPERDRIVE_PROD: "secret://doc-search/doc-search/prod/WIRING_CLOUDFLARE_HYPERDRIVE" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/web" + wranglerConfig: wrangler.jsonc + + # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets + # directory bound via ASSETS — both deploy in one `wrangler deploy`. + workerEntrypoint: .open-next/worker.js + assetsDir: .open-next/assets + + # Per-env worker name: doc-search-web-{dev,stage,prod}. + workerName: doc-search-web + environmentAwareWorkerName: true + + # The account's workers.dev subdomain; exported to the smoke step as + # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # wrangler.jsonc is COMMITTED — the fixture render, so the composition's + # structure check (`test -f wrangler.jsonc`, before the build, in a fresh + # checkout) passes. Stage and prod re-render it here, in their own job + # tree, from this environment's wiring document, so the Worker binds the + # real Hyperdrive config; dev verifies with the fixture and has no wiring. + # + # No public origin is baked in: the page renders no absolute URL (no Open + # Graph image, no canonical link), and every request it makes is to its + # own origin. ${ORUN_ENVIRONMENT} the runner sets for every step. + buildCommand: if [ "${ORUN_ENVIRONMENT}" != dev ]; then node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}"; fi && pnpm exec turbo run build --filter=@app/web + + # Smoke — and the docs' indexing, which is the step upstream ran at build + # time (`pnpm run embeddings`). After `wrangler deploy`: + # 1. the page renders (its search button is in the pre-rendered page); + # 2. POST /api/embeddings: the Worker embeds the docs it was built with + # through its AI binding and writes them through Hyperdrive — only + # the pages whose checksum the database does not hold, so a deploy + # that changed no doc embeds nothing — and answers "ok":true only if + # every page stored; + # 3. /api/health answers ok with sections in the index: the database + # reachable and migrated, the column at the embedding model's size, + # the docs there to search. + # No search is run, so no answer model is called. Each response is + # buffered before grep so an early match cannot SIGPIPE curl. + smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q 'Search...' && indexed=$(curl -sf -X POST \"${DEPLOYED_URL}/api/embeddings\") && echo \"${indexed}\" | grep -q '\"ok\":true' && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true' && ! echo \"${health}\" | grep -q '\"sections\":0'" + labels: + team: platform + layer: delivery + surface: web + runtime: cloudflare diff --git a/apps/web/components/SearchDialog.tsx b/apps/web/components/SearchDialog.tsx new file mode 100644 index 0000000..f5df60f --- /dev/null +++ b/apps/web/components/SearchDialog.tsx @@ -0,0 +1,170 @@ +'use client' + +import * as React from 'react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { useCompletion } from '@ai-sdk/react' +import { X, Loader, User, Frown, CornerDownLeft, Search, Wand } from 'lucide-react' + +export function SearchDialog() { + const [open, setOpen] = React.useState(false) + const [query, setQuery] = React.useState('') + + // AI SDK 5's hook (upstream's was AI SDK 2's `ai/react`): the route answers + // a plain text stream (`toTextStreamResponse()`), so the protocol is `text`. + const { complete, completion, isLoading, error } = useCompletion({ + api: '/api/vector-search', + streamProtocol: 'text', + }) + + React.useEffect(() => { + const down = (e: KeyboardEvent) => { + if (e.key === 'k' && e.metaKey) { + setOpen(true) + } + + if (e.key === 'Escape') { + console.log('esc') + handleModalToggle() + } + } + + document.addEventListener('keydown', down) + return () => document.removeEventListener('keydown', down) + }, []) + + function handleModalToggle() { + setOpen(!open) + setQuery('') + } + + const handleSubmit: React.FormEventHandler = (e) => { + e.preventDefault() + console.log(query) + complete(query) + } + + return ( + <> + + + + + OpenAI powered doc search + + Build your own ChatGPT style search with Next.js, OpenAI & Supabase. + +
+ +
+ +
+
+ {query && ( +
+ + {' '} + +

{query}

+
+ )} + + {isLoading && ( +
+ +
+ )} + + {error && ( +
+ + + + + Sad news, the search has failed! Please try again. + +
+ )} + + {completion && !error ? ( +
+ + + +

Answer:

+ {completion} +
+ ) : null} + +
+ setQuery(e.target.value)} + className="col-span-3" + /> + +
+
+ Or try:{' '} + +
+
+ + + +
+
+
+ + ) +} diff --git a/apps/web/components/ui/button.tsx b/apps/web/components/ui/button.tsx new file mode 100644 index 0000000..b49bfba --- /dev/null +++ b/apps/web/components/ui/button.tsx @@ -0,0 +1,47 @@ +import * as React from 'react' +import { VariantProps, cva } from 'class-variance-authority' + +import { cn } from '@/lib/utils' + +const buttonVariants = cva( + 'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-slate-400 focus:ring-offset-2 dark:hover:bg-slate-800 dark:hover:text-slate-100 disabled:opacity-50 dark:focus:ring-slate-400 disabled:pointer-events-none dark:focus:ring-offset-slate-900 data-[state=open]:bg-slate-100 dark:data-[state=open]:bg-slate-800', + { + variants: { + variant: { + default: 'bg-slate-900 text-white hover:bg-slate-500 dark:bg-slate-700 dark:text-slate-200', + destructive: 'bg-red-500 text-white hover:bg-red-600 dark:hover:bg-red-600', + outline: + 'bg-transparent border border-slate-200 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-100', + subtle: + 'bg-slate-100 text-slate-900 hover:bg-slate-200 dark:bg-slate-700 dark:text-slate-100', + ghost: + 'bg-transparent hover:bg-slate-100 dark:hover:bg-slate-800 dark:text-slate-100 dark:hover:text-slate-100 data-[state=open]:bg-transparent dark:data-[state=open]:bg-transparent', + link: 'bg-transparent dark:bg-transparent underline-offset-4 hover:underline text-slate-900 dark:text-slate-100 hover:bg-transparent dark:hover:bg-transparent', + }, + size: { + default: 'h-10 py-2 px-4', + sm: 'h-9 px-2 rounded-md', + lg: 'h-11 px-8 rounded-md', + }, + }, + defaultVariants: { + variant: 'default', + size: 'default', + }, + } +) + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps {} + +const Button = React.forwardRef( + ({ className, variant, size, ...props }, ref) => { + return ( +