Joel Stevick

Production RAG, line by line

Cloudflare in five minutes

The demo is three programs: demo.html in the visitor's browser, served by Cloudflare Pages; the site's Pages Functions; and a private Worker that the functions reach through the DEMO service binding. The Worker gets its D1 database, Vectorize index and Workers AI as bindings declared in wrangler.toml, and its model clients through createApp(modelsFor), so the deployed Worker, the tests and the evals each pass in their own.

Where each piece runs

Cloudflare Pages serves demo.html to the visitor's browser as a static file, and also runs the files under functions/ as Pages Functions: server code that runs on each request to its path, such as /api/demo/ask. The demo Worker is a separate program with no public address. A Worker is a script that Cloudflare runs on request: it exports a fetch(request, env, ctx) handler (and here a scheduled() handler too, for the daily job) and returns a Response.

The Pages Function calls the Worker through a service binding, which the function's code reaches as env.DEMO, an object of Cloudflare's Fetcher type. Calling env.DEMO.fetch(…) passes a Fetch API Request and returns a Response, but Cloudflare hands the request straight to the Worker's fetch() handler, by default on the same thread of the same server, with no added latency or cost, so the Worker needs no public URL. The Worker in turn calls D1, Vectorize, Workers AI, its KV namespace and the mailer through bindings of its own, and calls Anthropic's API with an ordinary fetch() and a secret key.

declaresreadsbindsBrowser: demo.html: the page; fetch('/api/demo/ask') from the visitor's browserBROWSERdemo.htmlthe page;fetch('/api/demo/ask')from the visitor'sbrowserPages Function: functions/api/demo/[[path]].ts: adds the visitor's key, then env.DEMO.fetch() to the WorkerPAGES FUNCTIONfunctions/api/demo/[[path]].tsadds the visitor's key,thenenv.DEMO.fetch() tothe WorkerDemo Worker: demo/src/index.ts: createApp(…): fetch(request, env, ctx) on each request, scheduled() once a day; calls Anthropic's API with the key from envDEMO WORKERdemo/src/index.tscreateApp(…):fetch(request, env,ctx) on each request,scheduled() once aday; calls Anthropic'sAPI with the key fromenvDemo Worker: env: built by Cloudflare for each call and passed into fetch() and scheduled(): every binding, as an object with the resource's methods, and every secret, as a stringDEMO WORKERenvbuilt by Cloudflare foreach call and passedinto fetch() andscheduled(): everybinding, as an objectwith the resource'smethods, and everysecret, as a stringwrangler.toml and secrets: declares each binding by name or id; the ANTHROPIC_API_KEY secret is set separately, with wrangler secret putwrangler.toml andsecretsdeclares eachbinding by name orid; theANTHROPIC_API_KEY secret is setseparately, withwrangler secret putCloudflare resource: D1: env.DB: SQLite database: demo accounts, files, chunks, questionsCLOUDFLARE RESOURCED1env.DB: SQLitedatabase: demoaccounts, files,chunks, questionsCloudflare resource: Vectorize: env.VECTORS: vector index, one namespace per demo accountCLOUDFLARE RESOURCEVectorizeenv.VECTORS:vector index, onenamespace perdemo accountCloudflare resource: Workers AI: env.AI: runs the bge-m3 embedding modelCLOUDFLARE RESOURCEWorkers AIenv.AI: runs thebge-m3 embeddingmodelCloudflare resource: KV: env.OAUTH_KV: the MCP server's OAuth clients, grants and token hashesCLOUDFLARE RESOURCEKVenv.OAUTH_KV: theMCP server's OAuthclients, grants andtoken hashes
Browser: the visitor's page: demo.html and its module scriptPages Function: the site's server code on Cloudflare Pages, functions/Demo Worker: the private Worker behind the DEMO service binding, demo/src/Cloudflare resource: storage or a model Cloudflare runs for the Worker, reached only through a binding

Injected resources: declared, delivered, used

A Worker never opens a connection string or holds a database password. demo/wrangler.toml declares each binding: a name for the code and the resource it stands for. When Cloudflare runs the Worker, it passes every binding in as a property of env, the second argument of fetch(). Each binding is an object whose methods call its resource: env.DB.prepare('SELECT …') runs SQL on the bound D1 database. The code describes env with the Env interface in demo/src/app.ts. wrangler.toml also binds OAUTH_KV (a KV namespace), MAILER (a service binding to another Worker, the mailer) and a [triggers] cron that runs scheduled() once a day.

A secret also arrives on env, but it is set with wrangler secret put (locally, in a git-ignored .dev.vars file), never written in wrangler.toml; the Worker has two, ANTHROPIC_API_KEY and DOCS_STORE_CLIENT_SECRET (the second is typed in demo/src/token-exchange.ts, not in Env). The site's own Pages configuration, which is not in this repository, declares the DEMO service binding the same way. wrangler deploy uploads the Worker with its configuration; the resources themselves are created once (wrangler d1 create, wrangler vectorize create), and the file refers to each by name or id.

The same code runs against other copies. evals/wrangler.toml binds the same names to a local D1 database and its own Vectorize index, joelstevick-com-demo-eval, so the eval harness never touches the demo's data, and the test suite gives the Worker a local D1 and KV of its own (demo/vitest.config.ts).

Cloudflare resource: [[d1_databases]] DB: the D1 database joelstevick-com-demosCLOUDFLARE RESOURCE[[d1_databases]]DBthe D1 databasejoelstevick-com-demosDemo Worker: env.DB: DB: D1DatabaseDEMO WORKERenv.DBDB: D1DatabaseDemo Worker: used as is: no wrapper: SQL through env.DB.prepare()DEMO WORKERused as isno wrapper: SQLthroughenv.DB.prepare()Demo Worker: app.ts, health.ts, mcp.ts, token-exchange.ts: route(), upload(), ask(), retrieval(), the daily job, the MCP tools, the document store's file listDEMO WORKERapp.ts, health.ts,mcp.ts,token-exchange.tsroute(), upload(),ask(), retrieval(), thedaily job, the MCPtools, the documentstore's file listCloudflare resource: [[vectorize]] VECTORS: the Vectorize index joelstevick-com-demoCLOUDFLARE RESOURCE[[vectorize]]VECTORSthe Vectorize indexjoelstevick-com-demoDemo Worker: env.VECTORS: VECTORS?: VectorizeIndexDEMO WORKERenv.VECTORSVECTORS?:VectorizeIndexDemo Worker: vectorsFor() → models.vectors: in index.tsDEMO WORKERvectorsFor() →models.vectorsin index.tsDemo Worker: upload(), retrieval(), remove(), purge(): upsert at INGEST 6, query at ASK 3–4, delete on removal and purgeDEMO WORKERupload(),retrieval(),remove(), purge()upsert at INGEST 6,query at ASK 3–4,delete on removaland purgeCloudflare resource: [ai] AI: Workers AI, running bge-m3CLOUDFLARE RESOURCE[ai] AIWorkers AI, runningbge-m3Demo Worker: env.AI: AI?: AiDEMO WORKERenv.AIAI?: AiDemo Worker: embedFor() → models.embed: in index.tsDEMO WORKERembedFor() →models.embedin index.tsDemo Worker: upload(), retrieval(): embeds the chunks at INGEST 6 and the question at ASK 3–4DEMO WORKERupload(),retrieval()embeds the chunksat INGEST 6 and thequestion at ASK 3–4Outside service: ANTHROPIC_API_KEY: a secret: wrangler secret put, or .dev.vars locallyOUTSIDE SERVICEANTHROPIC_API_KEYa secret: wranglersecret put, or.dev.vars locallyDemo Worker: env.ANTHROPIC_API_KEY: ANTHROPIC_API_KEY?: stringDEMO WORKERenv.ANTHROPIC_API_KEYANTHROPIC_API_KEY?: stringDemo Worker: claudeFor(), claudeStreamFor(): → models.claude and models.stream, in index.tsDEMO WORKERclaudeFor(),claudeStreamFor()→ models.claude andmodels.stream, inindex.tsDemo Worker: answering(): rerank at ASK 5 (models.claude), the answer at ASK 6–7 (models.stream)DEMO WORKERanswering()rerank at ASK 5(models.claude), theanswer at ASK 6–7(models.stream)Cloudflare resource: [[kv_namespaces]] OAUTH_KV: the KV namespace for OAuthCLOUDFLARE RESOURCE[[kv_namespaces]]OAUTH_KVthe KV namespacefor OAuthDemo Worker: env.OAUTH_KV: OAUTH_KV?: KVNamespaceDEMO WORKERenv.OAUTH_KVOAUTH_KV?:KVNamespaceDemo Worker: used as is: no wrapper: handed to the OAuth libraryDEMO WORKERused as isno wrapper: handedto the OAuth libraryDemo Worker: oauth.ts, token-exchange.ts: OAuth clients, grants and token hashes; store tokensDEMO WORKERoauth.ts,token-exchange.tsOAuth clients, grantsand token hashes;store tokensCloudflare resource: [[services]] MAILER: a service binding to the mailer WorkerCLOUDFLARE RESOURCE[[services]]MAILERa service binding tothe mailer WorkerDemo Worker: env.MAILER: MAILER?: FetcherDEMO WORKERenv.MAILERMAILER?: FetcherDemo Worker: used as is: no wrapper: passed to tellJoel(), which calls its fetch()DEMO WORKERused as isno wrapper: passedto tellJoel(), whichcalls its fetch()Demo Worker: upload(): INGEST 7 tells Joel about an account's first uploadDEMO WORKERupload()INGEST 7 tells Joelabout an account'sfirst upload
Demo Worker: the private Worker behind the DEMO service binding, demo/src/Cloudflare resource: storage or a model Cloudflare runs for the Worker, reached only through a bindingOutside service: a service off Cloudflare, reached with fetch() and a secret

How the Worker is handed its models

The pipeline never calls Claude, Workers AI or Vectorize directly. It calls a Models object (demo/src/models.ts) with four members: claude (one JSON reply), stream (the answer, streamed), embed (texts to vectors) and vectors (upsert, query, delete in the index). createApp(modelsFor) in demo/src/app.ts takes a function that builds that object from env, and calls it on every request, because env exists only inside a handler. This is dependency injection: whoever creates the app decides which models it gets.

Three places create it. demo/src/index.ts, the deployed Worker, passes the real clients built from the bindings and the secret. demo/tests/demo.test.ts passes scriptedModels() from tests/support/scripted.ts, which answer by markers in the question ([model-down], [vectors-down]…), so the suite never calls a model and can make each one fail on purpose. evals/worker.ts passes the real clients again, and wraps fetch to record every Claude call's tokens for the eval report.

The keyword search, BM25, is not a library or a Cloudflare service: it is bm25() in demo/src/retrieval.ts, about sixty lines of TypeScript. fuseKeywordAndVector() runs it over the demo account's chunks, which retrieval() read from D1, and merges its ranking with Vectorize's by reciprocal rank fusion.

Demo Worker: the private Worker behind the DEMO service binding, demo/src/Your machine: the developer's machine: npm test (vitest, demo/tests/), npm run eval (Node and wrangler dev, evals/) and npm run search (Node, examples/)

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.