Running it · Claude, Workers AI and Vectorize · stage 2 of 10
Model clients
The deployed implementations of the Models interface, which index.ts builds on each request. claudeFor and claudeStreamFor call the Messages API with fetch. claudeFor sends a structured-output request and returns the parsed JSON. claudeStreamFor sends a streamed request, parses its server-sent events with serverEvents, and yields the text_delta pieces. embedFor and vectorsFor wrap the Workers AI and Vectorize bindings (env.AI and env.VECTORS).
demo/src/models.ts167 / 167 lines on this page explainedlines 69-235 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
/** Claude through the Messages API, with structured output and no retries. */export function claudeFor(apiKey: string | undefined): Claude { return async ({ model, system, user, schema, maxTokens, timeoutMs, effort }) => {
A closure over the key Query time
WhatTakes the API key, which may be undefined, and returns an async function of the Claude type.
Whyindex.ts calls claudeFor(env.ANTHROPIC_API_KEY) on each request, because env exists only inside a handler. There are no retries. A failed call fails the rerank at once, and the rerank's fallback is faster than a retry.
// No key: throw at once, so the caller degrades exactly as it does when the model fails. if (apiKey === undefined || apiKey === '') throw new Error('no ANTHROPIC_API_KEY')
No key: throw Query time
WhatAn undefined or empty key throws "no ANTHROPIC_API_KEY" before any request, so the returned promise rejects.
WhyA Worker without the secret degrades the same way as when the model fails, and rerank falls back to fusion order.
// One request to the Messages API, asking for a reply in the schema's shape.const response = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', // The timeout aborts the request itself, so a slow model throws instead of holding the ask. signal: AbortSignal.timeout(timeoutMs), headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },
The request: endpoint, timeout, headers Query time
WhatPOST to https://api.anthropic.com/v1/messages with the key in x-api-key, anthropic-version 2023-06-01 and a JSON content type, and AbortSignal.timeout(timeoutMs) as the fetch signal.
WhyThe signal aborts both the request and the read of its body, so a slow model rejects with a TimeoutError instead of holding up the ask. The code calls the global fetch, which lets the eval harness wrap fetch to trace every Anthropic request (evals/worker.ts).
// Structured output: the schema makes the reply JSONofthis shape, so `JSON.parse` below is enough. output_config: { format: { type: 'json_schema', schema }, ...(effort === undefined ? {} : { effort }) }, }), })
Structured output, and effort Query time
Whatoutput_config.format is { type: 'json_schema', schema }, which constrains the reply's text to JSON that is valid against the schema. When effort is given, it goes in output_config too.
WhyBecause decoding is constrained, JSON.parse is enough, and no JSON has to be extracted from prose. Haiku 5.5 thinks by default (evals/JOURNAL.md, baseline). effort sets how much it thinks, and rerank asks for low. Without effort the field is omitted and the model's default applies.
// The body is read whether or not the call succeeded, since an error reply carries its message.const body = (await response.json()) as { content?: { type: string; text?: string }[]; error?: { message?: string } }if (!response.ok) thrownewError(`Anthropic ${response.status}: ${body.error?.message ?? ''}`)
Read the body, then check the status Query time
WhatThe JSON body is read first. On a non-2xx status the function throws "Anthropic <status>: <error.message>".
WhyAn API error response carries its reason in error.message (an invalid key, a rate limit, an overload), which is worth logging. A body that is not JSON, such as a proxy's HTML error page, makes response.json() throw a SyntaxError before the status check, and the caller degrades the same way.
// The reply's text blocks, joined; any other block, such as the model's thinking, is skipped.const text = (body.content ?? []).filter((block) => block.type === 'text').map((block) => block.text ?? '').join('')
Join the text blocks Query time
WhatKeeps the content blocks of type text and joins their text.
WhyWith thinking on, content holds a thinking block before the text block, and only the text block holds the JSON.
// Text that is not JSON throws here, which the caller treats as a failed call.returnJSON.parse(text) }}
Parse, or throw Query time
WhatReturns JSON.parse of the text.
WhyA reply cut off at max_tokens (stop_reason max_tokens) leaves no text block or truncated JSON, and JSON.parse throws. This is how the reranker with a 256-token limit failed in the evals' baseline. The code never reads the stop reason.
evals/JOURNAL.md, baseline: 4 of 25 rerank replies cut off at 256 tokens
/** * Claude through the Messages API, streamed, with no retries: the `text_delta` pieces of the reply * in order, as an async generator. * * With `stream: true` the API answers with a server-sent event stream instead of one JSON body. * The events that matter here, in the order they come: * message_start the reply has begun (its input token count is here; the eval trace reads it); * content_block_start a block begins: `thinking` first, since the model thinks before it writes, * then `text`; * content_block_delta a piece of the current block: `thinking_delta` (skipped here) or * `text_delta`, whose `text` is the next few characters of the answer; * message_delta the end is near: the stop reason and the output token count; * message_stop the end. * Only the `text_delta` pieces are yielded; the thinking is never shown or checked. An `error` * event (the API overloaded mid-reply) throws, which the caller treats as the model failing. */
The streaming events Never runs
WhatThe doc comment lists the stream's events in order: message_start, content_block_start (thinking, then text), content_block_delta (thinking_delta or text_delta), message_delta (stop reason, output tokens) and message_stop. An error event throws.
WhyThe stream also carries content_block_stop and ping events, and signature_delta on a thinking block. The list names only the events that matter here, and the code ignores every event except text_delta and error.
WhatReturns an async generator function of the ClaudeStream type.
WhyCalling a generator function runs none of its body, so answer() can return the stream unread, and no request is made until app.ts starts its for await.
// No key: throw on the stream's first read, so the caller degrades exactly as it does when the model fails. if (apiKey === undefined || apiKey === '') throw new Error('no ANTHROPIC_API_KEY')
No key: throw on the first read Query time
WhatAn undefined or empty key throws "no ANTHROPIC_API_KEY".
WhyBecause this is a generator body, the throw happens on the caller's first next(), inside its for await, as the comment says. The ask treats it as the model failing before anything was shown, and gives the question back.
// One streamed request to the Messages API. const response = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', // The timeout covers the whole reply, streamed or not: a model that stalls mid-answer aborts // the body, which throws out of the `for await` below. signal: AbortSignal.timeout(timeoutMs), headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },
The request, under one timeout Query time
WhatThe same endpoint and headers as claudeFor, with AbortSignal.timeout(timeoutMs) as the signal.
WhyThe signal covers the whole reply, including the body. A model that stalls mid-answer aborts the body read, which throws out of the for await. answer() sets 30 seconds.
// No `output_config`: the answer is plain text with inline citations (ANSWER_RULES), not JSON. body: JSON.stringify({ model, max_tokens: maxTokens, system, messages: [{ role: 'user', content: user }], stream: true }), })
stream: true, no output_config Query time
WhatThe body holds model, max_tokens, system, one user message and stream: true.
WhyWith stream: true the API responds with a text/event-stream body. There is no structured output because the answer is prose with inline citations (ANSWER_RULES), and no effort, so the answer model runs at its default.
// An error reply (a bad key, a rate limit) is one JSON body, not a stream; its message is kept. if (!response.ok || response.body === null) { const body = (await response.json().catch(() => ({}))) as { error?: { message?: string } } throw new Error(`Anthropic ${response.status}: ${body.error?.message ?? ''}`) }
An error before the stream Query time
WhatOn a non-2xx status, or a missing body, it reads the body as JSON (an empty object if that fails) and throws "Anthropic <status>: <message>".
WhyAn error detected before streaming starts (a bad key, a rate limit, a 529 overload) comes back as one JSON body with an HTTP error status.
// Each server-sent event's data is one JSONobject; only the text pieces are passed on.forawait (const event of serverEvents(response.body)) {const data = JSON.parse(event.data) as { type?: string; delta?: { type?: string; text?: string }; error?: { message?: string } }if (data.type === 'content_block_delta' && data.delta?.type === 'text_delta') yield data.delta.text ?? ''
Yield each text_delta Query time
WhatEach server-sent event's data is parsed as JSON. A content_block_delta whose delta is a text_delta yields delta.text, and every other event is ignored. Data that is not JSON throws a SyntaxError, which the ask treats as the model failing.
WhyThe text_delta pieces are the visible answer, and thinking deltas are never shown or checked. The code does not read message_delta's stop_reason either, so an answer cut off at max_tokens ends there, and its last, unfinished unit (a sentence or list item) is checked like any other at release(true).
WhatAn event of type error throws "Anthropic stream: <message>".
WhyOnce streaming has begun, the HTTP status is already 200, so an overload during the reply arrives as an error event. The throw reaches the ask's catch. If nothing was shown, the question is given back; otherwise the answer stops where it is.
/** * The events of a server-sent event stream, each with its name and its data, as an async generator. * * The wire format (text/event-stream) is lines: "event: <name>", one or more "data: <text>", * other fields ignored here, and a blank line ending each event. The body arrives in chunks that * end anywhere, mid-line included, so the decoded text is kept in `buffer` and only whole events, * those followed by a blank line, are taken out of it; the remainder waits for the next chunk. */
The wire format Never runs
WhatThe doc comment gives the format: event: and data: lines, other fields ignored, and a blank line ending each event. Network chunks can end anywhere, so the text is buffered and only whole events are taken out.
WhySplitting each network chunk separately would cut events, and even lines, in half.
exportasyncfunction* serverEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<{ event: string; data: string }> { // Bytes to text as they come; a multi-byte character split across two chunks is joined by the decoder.const reader = body.pipeThrough(new TextDecoderStream()).getReader() // Text received but not yet split into whole events.let buffer = ''
Decode as it comes Query time
WhatPipes the body through a TextDecoderStream and takes a reader. buffer holds decoded text not yet split into events.
WhyTextDecoderStream keeps a UTF-8 character that is split across two network chunks whole. Decoding each chunk separately would corrupt it.
// The `finally` runs however the generator ends: the stream read to its end, an exception, or // the caller leaving its `for await` early (`return()` on the generator). Cancelling the reader // then cancels the HTTP body, so a reply the demo has stopped reading (a sentence failed its // check) is not read, or paid for, to its end.try {
The finally cancels the body Query time
WhatThe loop is inside try/finally. The finally runs when the stream ends, on an exception, or when the consumer leaves its for await early, which calls return() on the generator.
WhyWhen a sentence fails its check, the ask breaks out of its loop. That calls return() on claudeStreamFor's generator, which calls return() on this one, and the finally cancels the HTTP body. The rest of a refused answer is then neither read nor generated, so it is not paid for.
The same idea, shown in the episode's own code: Stopping a for await loop: return, finally and cancelling From Streaming for RAG engineers, Ep 1: Async Generators: Streaming, Step by Step
for (;;) {const { value, done } = await reader.read() // Line endings normalised, so the blank line that ends an event is always "\n\n".if (value !== undefined) buffer += value.replace(/\r\n/g, '\n')
Read, normalise line endings Query time
WhatReads the next decoded chunk and appends it to buffer with CRLF replaced by LF.
WhyAfter the replace, the blank line that ends an event is always "\n\n". The replace runs per chunk, so it would miss a CRLF pair split across two chunks, which cannot happen with a server that ends lines with LF alone. A lone CR, which the standard also allows as a line ending, is not treated as a line end.
// Each event ends at a blank line; what follows the last one waits for more.let end: numberwhile ((end = buffer.indexOf('\n\n')) >= 0) {const block = buffer.slice(0, end) buffer = buffer.slice(end + 2)
Take out each whole event Query time
WhatWhile buffer contains "\n\n", the text before it is one event block, and the block and its terminator are removed from buffer.
WhyAny text after the last blank line is an incomplete event and waits for the next chunk.
// An event with no "event:" line is named "message", as the standard says.let event = 'message'const data: string[] = []for (const line of block.split('\n')) {if (line.startsWith('event:')) event = line.slice(6).trim() // Several "data:" lines are one payload, joined with newlines; the space after the colon is not part of it.elseif (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, '')) }
Read its fields Query time
WhatThe name defaults to "message". An event: line sets it (trimmed), and each data: line adds its value without one leading space. Other lines (id:, retry:, comments starting with a colon) are ignored.
WhyThis follows the HTML standard's event-stream rules: the default name, one optional space removed from data, and several data lines joined with newlines. The code departs from the standard in three ways, none of which occurs in the Messages API's stream. It trims the name, where the standard removes one leading space. An empty event: value gives the name '', where the standard uses 'message'. A bare data line with no colon is ignored, where the standard adds an empty data line.
// Stop once the stream has ended.if (done) return }
Stop at the end Query time
WhatOnce the reader reports done, the generator returns.
WhyEvery whole event in the final chunk was already yielded by the loop. Text after the last blank line is dropped, as the standard drops an unterminated event at the end of the stream.
/** bge-m3 on Workers AI as an `Embed`; undefined without the AI binding, so the demo runs on keywords alone. */exportfunction embedFor(ai: Ai | undefined): Embed | undefined { // No AI binding: no embeddings, so keyword search only.if (ai === undefined) returnundefined
No AI binding: undefined Query time
WhatWithout the AI binding it returns undefined.
WhyModels.embed is then undefined, so upload skips INGEST 6 and retrieval skips the vector search, and the demo app answers from BM25 alone instead of failing.
// `ai.run` is typed per model; cast once to what bge-m3 returns: one vector per text, in order.const run = ai.run.bind(ai) asunknownas (model: string, input: unknown) => Promise<{ data: Vector[] }>
One cast to bge-m3's return type Query time
Whatai.run, bound to ai, is cast to a function of a model name and an input that returns { data: Vector[] }.
WhyThe Workers AI types are overloaded per model. The cast states the one shape this code relies on, bge-m3's data array of vectors.
// Embed all the texts in one call and return just the vectors.returnasync (texts) => (await run(EMBEDDING_MODEL, { text: texts })).data}
Embed in one call Query time
WhatRuns @cf/baai/bge-m3 with { text: texts } and returns its data: one 1,024-dimension vector per text, in order.
WhyThere is no try/catch here, so a Workers AI error throws to the caller. upload catches it and keeps the file searchable by keywords, and retrieval catches it and uses BM25 alone. upload sends 50 texts a call (EMBED_BATCH). It runs at both times: on an upload, to embed the chunks (INGEST 6), and on a question, to embed the question (ASK 3). It is marked Query time, the value for code that runs on both.
/** The Vectorize index as `Vectors`; undefined without the binding. */exportfunction vectorsFor(index: VectorizeIndex | undefined): Vectors | undefined { // No Vectorize binding: no vector search.if (index === undefined) returnundefined
No Vectorize binding: undefined Query time
WhatWithout the VECTORS binding it returns undefined.
WhyModels.vectors is then undefined, with the same effect as a missing embedding model: keyword search alone.
return {async upsert(namespace, items) { // Every vector is written under the demo's namespace, so a query in that namespace sees that demo's vectors alone.await index.upsert(items.map((item) => ({ ...item, namespace }))) },
upsert(): writes in the account's namespace Ingestion
WhatAdds the namespace to each { id, values } and calls index.upsert with the list.
WhyThe namespace, the account's own partition of the vector index, is named by the demo account's id, so a query in that namespace sees only that account's vectors. Vectorize applies writes asynchronously, so a vector becomes searchable shortly after the upsert returns.
async query(namespace, values, topK) { // Vectorize returns matches best first; only the ids are kept, the chunks are read from D1 by id.return (await index.query(values, { topK, namespace })).matches.map((match) => match.id) },
query(): the ids, best first Query time
WhatCalls index.query(values, { topK, namespace }) and returns the matches' ids, best first.
WhyThe scores are dropped because the chunk text is read from D1 by id and reciprocal rank fusion uses only ranks. Without returnValues or returnMetadata, Vectorize returns only ids and scores.
async deleteByIds(ids) { // Vectorize deletes by id alone; a chunk id starts with its demo's id, so only that demo's vectors go.await index.deleteByIds(ids) }, }}
deleteByIds(): by id, in any namespace Site request
WhatCalls index.deleteByIds(ids) with no namespace.
WhyVectorize deletes by id alone. Every chunk id begins with its demo account's id, so only that account's vectors are deleted. Two callers send it up to 500 ids per call: remove(), on a site request (DELETE /api/demo/files) or on an MCP request (remove_file), and purge(), in the daily scheduled job, which deletes an idle account's vectors. It is marked Site request, for the page's removal; on the purge it runs as Scheduled.