Joel Stevick

Running it · What the pipeline calls · stage 1 of 10

The Models interface

Every model call and the vector index go through one object, Models, with four members: claude (one JSON reply), stream (the answer as text pieces), and embed and vectors. The pipeline reaches D1 directly through env.DB, outside Models. createApp takes a function that builds a Models on each request from env, the object Cloudflare passes to the Worker, holding the API key secret and the Workers AI and Vectorize bindings. The deployed demo app and the eval harness build it from the real clients, and the harness traces their requests by wrapping fetch. The tests pass scripted implementations to the same routes.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/models.ts68 / 68 lines on this page explainedlines 1-68 of 355; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own

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

demo/src/models.ts The model clients and prompts: lines 1–68, the model ids and the types every client implements.

Module scope

module scope · lines 1–11View on GitHub

The licence, the module's purpose, and the Chunk import.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under MIT, and tools read the licence from the SPDX line.

/** * The models the demo calls, each behind a small interface so the suite can * script them: Claude (the rerank and the answer), the embedding model and the * vector index. */

Why each model is behind an interface Never runs

WhatThe doc comment names the three models the demo app calls: Claude for the rerank and the answer, the embedding model, and the vector index. Each one is behind a small interface.

WhyThe routes depend only on these types, so the test suite passes scripted implementations (tests/support/scripted.ts) and runs the whole pipeline without a network call.

The same idea, shown in the course's code: The models interface: chat and embed passed in as a dependency From Prove it works, Ep 2: Models as a parameter
import type { Chunk } from './retrieval'

The Chunk type Type only

WhatA type-only import of Chunk from retrieval.ts, which the compiler erases.

Whyrerank() and answer(), later in this file, take and return chunks.

ANSWER_MODEL, RERANK_MODEL, EMBEDDING_MODEL

constant · lines 12–16View on GitHub

The three model identifiers.

/** Claude Sonnet writes the answer; Claude Haiku, faster and cheaper, reranks; bge-m3 on Workers AI embeds the chunks and the question. */export const ANSWER_MODEL = 'claude-sonnet-5-5'export const RERANK_MODEL = 'claude-haiku-5-5'export const EMBEDDING_MODEL = '@cf/baai/bge-m3'

Which model does what Module load

WhatClaude Sonnet 5.5 writes the answer, Claude Haiku 5.5 reranks, and bge-m3 on Workers AI embeds the chunks at ingestion and the question at query time.

WhyThe rerank reads up to 48 passages for every question, so it uses the faster, cheaper model. The answer must cite its passages and stay within them, so it uses the stronger model. The eval harness's trace (evals/worker.ts) imports RERANK_MODEL and ANSWER_MODEL to tell the two calls apart.

ANSWER_MODEL = 'claude-sonnet-5-5'RERANK_MODEL = 'claude-haiku-5-5'EMBEDDING_MODEL = '@cf/baai/bge-m3'

Claude

type · lines 17–28View on GitHub

One structured-output call to Claude, returning the parsed JSON.

/** One JSON reply from Claude, parsed. Throws on anything else, so the caller degrades. */export type Claude = (request: {  model: string  system: string  user: string  schema: Record<string, unknown>  maxTokens: number  timeoutMs: number  /** How hard the model thinks, where the model's default does not fit. */  effort?: 'low'}) => Promise<unknown>

One JSON reply Type only

WhatA function that takes the model, the system prompt, the user message, a JSON Schema, a token limit, a timeout and an optional effort of 'low', and returns a Promise of the parsed reply, typed unknown.

WhyThe contract is that it throws on any failed call and on any reply that is not JSON, so the caller catches every failure in one try/catch. Structured output makes the JSON follow the schema, but the result is typed unknown, so the caller still validates it. rerank(), the only caller in the pipeline, does.

ClaudeStream

type · lines 29–43View on GitHub

Claude's reply as text pieces, read with for await.

/** * Claude's reply as it is written: the text, a piece at a time, through the Messages API's * streaming. It is an `AsyncIterable<string>`: the caller reads it with `for await`, each value * being the next few characters of the reply, and leaving the loop early stops the call. Throws * when the call fails, before or during the text, so the caller degrades. The suite scripts one in * tests/support/scripted.ts (`stream`); the deployed demo uses `claudeStreamFor`. */

The reply as it is written Never runs

WhatThe doc comment states the contract. The stream is an AsyncIterable<string>, and each value is the reply's next few characters. Leaving the for await early stops the call. A failure throws, before or during the text.

WhyThe ask checks each sentence as soon as it is complete (ASK 6–7), so it needs the text as it arrives. Because leaving the loop stops the call, a refused answer stops costing tokens.

export type ClaudeStream = (request: {  model: string  system: string  user: string  maxTokens: number  timeoutMs: number}) => AsyncIterable<string>

The signature Type only

WhatThe same request as Claude without schema and effort, returning AsyncIterable<string>.

WhyThe answer is plain text with inline citations, so there is no schema. answer() returns the iterable without reading it, so the HTTP request starts only when app.ts begins iterating.

Vector, Embed

type · lines 44–49View on GitHub

An embedding, and the function that makes them.

/** An embedding: one text as a point in the embedding model's space (bge-m3: 1,024 numbers). */export type Vector = number[]

Vector: 1,024 numbers from bge-m3 Type only

WhatA plain number array. bge-m3 returns 1,024 numbers.

WhyVectorize stores and compares these arrays. A query vector must have the index's dimension, so the question and the chunks are embedded by the same model.

/** The texts as vectors, one per text, in the same order. */export type Embed = (texts: string[]) => Promise<Vector[]>

Embed: texts to vectors, in order Type only

WhatTakes a list of texts and returns one vector per text, in the same order.

WhyOrder is the only link between a text and its vector. upload pairs vector j with chunk j of each batch of 50 (EMBED_BATCH), and retrieval takes the single vector returned for the question.

Vectors

interface · lines 50–59View on GitHub

The vector index, partitioned by demo account.

Called by purge() Idle purge and expiry remove() Removing a file retrieval() Retrieval upload(): INGEST 6 Embed and index

/** The vector index, holding each demo's chunk vectors in a namespace of its own. */export interface Vectors {  /** Writes each id's vector into `namespace`, replacing any vector already stored under that id. */  upsert(namespace: string, items: { id: string; values: Vector }[]): Promise<void>  /** The nearest ids in `namespace`, best first. */  query(namespace: string, values: Vector, topK: number): Promise<string[]>  /** Removes these ids' vectors, whatever namespace they are in. */  deleteByIds(ids: string[]): Promise<void>}

Upsert, query, delete Type only

Whatupsert writes each id's vector into a namespace and replaces any vector already stored under that id. query returns the topK nearest ids in a namespace, best first, without scores. deleteByIds removes vectors by id and takes no namespace.

WhyA namespace is a partition of the Vectorize index that a query searches on its own; each demo account's namespace is named by its id, so a query never reaches another account's vectors. query returns ids only, because the chunk text is read from D1 and reciprocal rank fusion uses ranks alone. Deleting by id alone is safe because every chunk id begins with its account's id, so no other account has a vector with the same id.

Models

interface · lines 60–68View on GitHub

Everything the pipeline calls, in one object.

Called by retrieval() Retrieval upload(): INGEST 6 Embed and index

/** What a demo calls. Without `embed` or `vectors` (no Workers AI or Vectorize binding), it answers from keyword search alone. */export interface Models {  claude: Claude  /** The answer model, streamed. */  stream: ClaudeStream  embed?: Embed  vectors?: Vectors}

What the demo app calls Type only

Whatclaude and stream are required; embed and vectors are optional. The deployed Worker builds a Models on each request from its bindings (index.ts). The eval harness (evals/worker.ts) builds its own from the same real clients, and the tests pass scripted ones (tests/support/scripted.ts).

WhyThe two Claude members are always present because their clients fail at call time when the API key is missing, and the pipeline degrades at that point. embed and vectors are undefined when the Worker has no AI or VECTORS binding. upload then skips INGEST 6, and retrieval answers from BM25 alone.