Cloudflare 17 ☁️ Workers AI, Vectorize & Agents — Running serverless GPU inference, RAG with Vectorize, AI Gateway, and stateful Agents/MCP servers
Four products, one pipeline. Workers AI runs a model on Cloudflare’s GPU fleet from inside a Worker, with no endpoint to provision and no container to keep warm. Vectorize stores the embeddings that model produces and answers a nearest-neighbour query over them. AI Gateway sits in front of either of those — or in front of OpenAI, Anthropic, or anything else with an HTTP API — and adds caching, rate limiting, retries, fallbacks, and logs without changing the caller. Agents is the stateful layer that holds a conversation across requests and exposes tools to a model, including over the Model Context Protocol.
The reason they belong in one chapter is that a retrieval-augmented generation request touches all four in sequence: embed the question, search the index, assemble a prompt, call the model, and stream the answer back — while every call passes through a gateway that records what it cost. Each product has a failure mode that is invisible until production: a dimension mismatch between the embedding model and the index, a topK that silently drops the answer because the chunking split it in two, a cached response that outlives the document it summarised, and an agent loop that calls the same tool eleven times because nothing bounded it.
The chapter works through them in dependency order. Workers AI first, because it produces the vectors. Vectorize second, because it stores and searches them. AI Gateway third, because it is the policy layer that wraps both and everything else. Agents last, because it is the layer that makes the whole thing conversational and, in the MCP form, exposes it to someone else’s client.
Key point: Workers AI, Vectorize, and Agents are three different state models — stateless inference, a persistent index, and a Durable Object per conversation — and confusing them is where the bugs come from; AI Gateway is the one layer that assumes nothing about any of them and can therefore cache, limit, and log all three uniformly.
Why it exists
The inference-placement problem. Running a model from a Worker means the network hop between the request handler and the GPU is inside Cloudflare’s network rather than over the public internet from a serverless function to a model provider. For a small model that is the difference between a 40 ms round trip and a 400 ms one, and it is the difference between a request that fits in a Worker’s CPU budget and one that does not. The binding model also removes the credential: env.AI.run(...) has no API key to leak, because the permission is the binding in the deployment config.
The embedding-storage problem. A vector is not a row. It is 768 floats for the smallest useful model and 1024 or 1536 for better ones, and a relational database stores it badly and searches it worse. Vectorize is the answer for the retrieval half: an index whose dimensions are fixed at creation, whose distance metric is fixed at creation, and whose query accepts a metadata filter that runs before the similarity comparison rather than after.
The gateway problem. An application that calls a model directly has no place to put the four things that every production AI feature eventually needs: a cache, a rate limit, a fallback when the primary provider is slow, and a log of what was sent and what it cost. Adding those to the application means four reinventions. AI Gateway is that layer externally, addressed by URL, with the caller changing one base URL and nothing else.
The state problem. A Worker is stateless per request, which makes a conversation awkward: every turn must either resend the whole transcript or store it somewhere with a key. Agents makes the storage the object — each conversation is a Durable Object with its own SQLite and its own WebSocket connections, so the transcript is local, the streaming is resumable, and the tool loop can run for minutes rather than for the length of one request.
The MCP problem. The Model Context Protocol standardises how a model discovers and calls tools. Exposing your own tools over it means someone else’s client — an IDE, a desktop assistant, another agent — can call them, and doing that from a Worker requires an SSE or streamable-HTTP transport plus per-session state. McpAgent is the Durable Object that supplies both, so the work is writing the tool definitions rather than the transport.
The cold-start problem. Serverless inference is not free of latency; the first call to a model that has not been used recently pays a load cost. The mitigation is design rather than configuration: stream the first tokens back so the user sees progress, keep the prompt small enough that prefill is fast, and pick a model whose size matches the task rather than defaulting to the largest one available.
The trade-off. Every choice here narrows something. A small model is fast and worse at reasoning. A fixed set of dimensions means a re-embed and a re-index if you change models. Gateway caching means a stale answer can be served for the length of the TTL. Agent state means a Durable Object that bills while it exists and needs a schema migration when its shape changes. The design question is which of those costs less than the alternative.
a. Workers AI — the binding, the model id, and the four call shapes
The binding is declared in the Wrangler config and used as env.AI. The call is always env.AI.run(model, inputs), and the model id is a string beginning with @cf/, which is the namespace for Cloudflare-hosted models.
// wrangler.jsonc — the binding is the credential; there is no API key
{
"ai": { "binding": "AI" },
"compatibility_date": "2025-04-01"
}
Four call shapes cover almost everything. Chat takes a messages array and returns { response }. Embeddings take a text array and return { data }, one vector per string. Streaming is the chat shape plus stream: true, and returns a ReadableStream you hand straight to the Response. Structured output is the chat shape plus a JSON schema, and returns an object that parses without a repair step.
// Chat: a system turn and a user turn, capped and temperature-controlled
const out = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages: [
{ role: "system", content: "Answer in one sentence. Cite the source." },
{ role: "user", content: question },
],
max_tokens: 256, // hard cap; the bill is per token generated
temperature: 0.2, // low: this is a retrieval answer, not a story
});
return Response.json({ answer: out.response });
// Embeddings: one call embeds many strings, which is the cheap way to backfill
const { data } = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: chunks, // batched; a single round trip for the whole page
});
// data is an array of 768-length float arrays, aligned with `chunks`
console.log(chunks.length, data.length, data[0].length); // 12 12 768
The dimension count is the contract with Vectorize and it differs per model: @cf/baai/bge-small-en-v1.5 is 384, @cf/baai/bge-base-en-v1.5 is 768, @cf/baai/bge-large-en-v1.5 and @cf/baai/bge-m3 are 1024. An index created at 768 cannot accept a 1024 vector, and the error arrives at upsert time rather than at creation time, which is why the model id belongs next to the index name in the code.
// Streaming: the stream is the response body; the client sees tokens immediately
const stream = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages,
stream: true,
});
return new Response(stream, {
// Workers AI emits server-sent events, not raw text
headers: { "content-type": "text/event-stream", "cache-control": "no-store" },
});
// Structured output: the schema becomes the contract, not a suggestion
const { response } = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages: [{ role: "user", content: `Classify: ${ticket}` }],
response_format: {
type: "json_schema",
json_schema: {
type: "object",
properties: {
category: { type: "string", enum: ["billing", "bug", "other"] },
confidence: { type: "number" },
},
required: ["category", "confidence"],
},
},
});
// response is a JSON string that matches the schema; parse it, then validate
const parsed = classifySchema.parse(JSON.parse(response));
Usage is metered in Neurons, a model-weighted unit rather than a token count, which means the price of a call depends on which model ran and how many tokens it read and wrote. The free allocation is 10,000 Neurons per day per account, and the paid rate is $0.011 per 1,000 Neurons — enough to make an untested loop visibly expensive within a day. The practical consequence is that max_tokens is a cost control, not a style preference, and that a batch of 40 embedding calls is worth collapsing into one text array.
Model selection is a size question. The 8B-class instruct models handle extraction, classification, summarisation, and short retrieval answers. The 70B-class models are for reasoning where the extra latency is justified. Embedding and reranking models are fixed by the retrieval task rather than by preference. Image and speech models (@cf/black-forest-labs/flux-1-schnell, @cf/openai/whisper) share the same binding and the same billing unit, which is why a single gateway in front of all of them is worth the setup.
b. Vectorize — dimensions, chunking, metadata filters, and the query shape
An index is created with a dimension count, a distance metric, and nothing else that can be changed afterwards. The metric matters more than it looks: cosine normalises before comparing and is the right default for text embeddings; dot-product is faster and equivalent only when the vectors are already normalised; euclidean is for cases where magnitude carries meaning.
# Create once; dimensions and metric are immutable from that point on
wrangler vectorize create docs --dimensions=768 --metric=cosine
# Metadata filtering needs an index per property, created before it is queried
wrangler vectorize create-metadata-index docs --property-name=lang --type=string
wrangler vectorize create-metadata-index docs --property-name=year --type=number
Chunking is the decision that determines whether retrieval works. A chunk that is too large buries the answer in noise; a chunk that is too small splits a fact across two records so neither retrieves cleanly. The working heuristic for prose is roughly 200–400 tokens with a 10–20% overlap, split on paragraph or heading boundaries rather than on a fixed character count, and each chunk carries its parent document id as metadata so the surrounding context can be fetched after the match.
// Chunk, embed, and upsert in one pass
const chunks = splitByHeading(document.text, { maxTokens: 300, overlap: 40 });
const { data } = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: chunks.map(c => c.text), // batch, not one call per chunk
});
await env.VECTORIZE.upsert(
chunks.map((chunk, i) => ({
// The id embeds the parent so a single chunk can be deleted with it
id: `${document.id}#${i}`,
values: data[i],
metadata: {
docId: document.id,
text: chunk.text, // stored so the prompt needs no join
heading: chunk.heading,
lang: document.lang,
year: document.year,
},
namespace: "prod", // separates environments in one index
})),
);
The query is where the limits show. topK is capped, and the cap is lower when values or metadata come back — the documented ceiling is 20 with metadata and 100 for ids only. That ceiling is why retrieval is usually two-stage: fetch a wider candidate set with ids, then rerank or re-read to pick the handful that go into the prompt.
// Query: embed the question, filter before comparing, return metadata
const [{ values: qvec }] = (await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: [question],
})).data.map(values => ({ values }));
const hits = await env.VECTORIZE.query(qvec, {
topK: 8,
returnMetadata: "all", // needed for the prompt and for citations
namespace: "prod",
// The filter runs before the similarity search, not after it
filter: {
lang: { $eq: "en" },
year: { $gte: 2023 },
},
});
// hits.matches is ordered by score, descending
const context = hits.matches.map(m => m.metadata.text).join("\n\n---\n\n");
Four operators cover most filters — $eq, $ne, $in, $nin, plus the range comparisons $lt, $lte, $gt, $gte on numeric properties — and a $and / $or wrapper combines them. The property must have a metadata index created before the query, and a filter on an unindexed property either errors or matches nothing depending on the API version, which is the kind of failure that looks like “retrieval is bad” rather than “the filter is wrong”.
// Deleting a document means deleting every chunk that carries its id
const ids = await listChunkIds(document.id); // from your own store, not the index
await env.VECTORIZE.deleteByIds(ids);
A namespace inside an index separates production from staging or one tenant from another without a second index, and it is part of the query rather than part of the filter. Use it for a coarse partition that is known at call time, and metadata for a fine one that varies per query.
For a pipeline that is entirely Cloudflare-hosted content — documents in R2, a fixed chunking strategy, no custom preprocessing — AutoRAG wraps the index, the chunking, and the query into a single binding, and is worth knowing about before hand-rolling the loop above.
c. AI Gateway — the URL, the universal endpoint, and the four controls
AI Gateway is addressed by URL rather than by binding, which is the design decision that makes it work with any provider and any runtime, not just Workers. The shape is https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway}/{provider}/{path}.
Workers AI /v1/{acct}/{gw}/workers-ai/@cf/meta/llama-3.1-8b-instruct
OpenAI /v1/{acct}/{gw}/openai/chat/completions
Anthropic /v1/{acct}/{gw}/anthropic/v1/messages
Google AI /v1/{acct}/{gw}/google-ai-studio/v1beta/models/...
// The same call as before, routed through the gateway for logging and cache
const res = await fetch(
`https://gateway.ai.cloudflare.com/v1/${env.ACCOUNT_ID}/${env.GATEWAY}/workers-ai/@cf/meta/llama-3.1-8b-instruct`,
{
method: "POST",
headers: {
"content-type": "application/json",
// Cache this answer for ten minutes; skip it for anything user-specific
"cf-aig-cache-ttl": "600",
// Arbitrary JSON stored alongside the log entry, filterable in the UI
"cf-aig-metadata": JSON.stringify({ feature: "support", userId: user.id }),
},
body: JSON.stringify({ messages, max_tokens: 256 }),
},
);
// The response reports whether the cache was used
const cacheStatus = res.headers.get("cf-aig-cache-status"); // HIT or MISS
Caching is keyed on the request body plus the URL, and the headers that control it are cf-aig-cache-ttl in seconds, cf-aig-skip-cache to bypass a stored entry, and cf-aig-cache-key to override the derived key — the last of which matters when the body contains a timestamp that would otherwise make every request a miss. The rule worth internalising is that a cached RAG answer outlives the document it was generated from, so personal or fresh-content queries set cf-aig-skip-cache: true rather than fighting with TTLs.
Rate limiting is configured on the gateway rather than requested per call, and the technique is fixed or sliding window by key — the caller’s IP, their API key, or a header value you choose. That is the difference from a Worker-side limiter: the gateway limit applies to traffic you can see, and it applies before the provider is billed.
// The universal endpoint: an array of provider requests, tried in order
const res = await fetch(
`https://gateway.ai.cloudflare.com/v1/${env.ACCOUNT_ID}/${env.GATEWAY}`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify([
{ provider: "workers-ai", endpoint: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
headers: { "cf-aig-metadata": '{"path":"primary"}' }, query: { messages } },
{ provider: "workers-ai", endpoint: "@cf/meta/llama-3.1-8b-instruct",
headers: { "cf-aig-metadata": '{"path":"fallback"}' }, query: { messages } },
]),
},
);
The array is a fallback chain: the gateway tries the first entry and moves to the next when it fails, so a provider outage or a model overload becomes a slower answer rather than an error. That chain is worth building before it is needed, because the moment it is needed is the moment nobody wants to be editing config.
Two related settings finish the picture. Request timeout bounds a slow provider so the fallback can fire rather than the request hanging until the Worker’s own limit. Logging records the request, the response, the token usage, the cost, and the metadata header, with a retention window on the free tier that is shorter than the paid one — which is why production gateways are usually upgraded and why the metadata header should carry enough to filter the log by feature and by user without storing anything sensitive in it.
d. Agents and MCP — a Durable Object per conversation and a tool surface for someone else’s client
An Agent is a Durable Object with a state document, a SQLite database, WebSocket connections, and a scheduler. It is declared as a class, exported, and routed by URL. Each instance is identified by a name derived from the request, so a conversation id in the path becomes a distinct object with its own memory.
// The class is the agent; the instance is the conversation
import { Agent, routeAgentRequest } from "agents";
type State = { transcript: { role: string; content: string }[]; turns: number };
export class Support extends Agent<Env, State> {
initialState: State = { transcript: [], turns: 0 };
async onRequest(req: Request) {
const { message } = await req.json<{ message: string }>();
// State is read and written through the object, not passed around
const next = { ...this.state, turns: this.state.turns + 1 };
this.setState(next);
// The binding is available as this.env, exactly as in a Worker
const out = await this.env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages: [{ role: "user", content: message }],
});
return Response.json({ reply: out.response, turns: next.turns });
}
}
export default {
// The router maps /agents/support/<name> to the object named <name>
fetch: (req, env, ctx) =>
routeAgentRequest(req, env) ?? new Response("not found", { status: 404 }),
};
State reaches the client without a request. this.setState() persists and broadcasts to every connected WebSocket, which is what makes a multi-tab conversation stay in sync without polling, and hibernation means an idle object with open connections does not bill for duration.
export class Support extends Agent<Env, State> {
// Fires whenever the state changes, including on another tab's update
onStateUpdate(state: State, source: "server" | "client") {
// The source distinguishes a local write from a broadcast received
console.log({ turns: state.turns, source });
}
async onConnect(conn: Connection, ctx: ExecutionContext) {
// Send the current transcript to a client that just attached
conn.send(JSON.stringify({ type: "transcript", data: this.state.transcript }));
}
async onMessage(conn: Connection, raw: string) {
const msg = JSON.parse(raw);
await this.onRequest(new Request("https://x/", { method: "POST", body: JSON.stringify(msg) }));
}
}
Work that outlives a request goes through the scheduler, which persists the callback and fires it even across a redeploy. That is how a long tool loop runs without holding a connection open and how a digest gets sent an hour later.
// Schedule work on the object; it survives restarts and deploys
await this.schedule(new Date(Date.now() + 60_000), "recheck", { ticketId });
await this.scheduleEvery(3600, "refreshCache"); // recurring, per object
// SQLite is available directly on the object for anything state does not fit
const rows = this.sql<{ id: string; body: string }>`
SELECT id, body FROM messages WHERE ticket = ${ticketId} ORDER BY ts DESC LIMIT 20
`;
The MCP form is the same machinery pointed outward. McpAgent extends the Agent with an McpServer, you declare tools in init(), and the class is served over one or both transports — /sse for the older transport and /mcp for streamable HTTP.
import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
export class DocsMcp extends McpAgent<Env, Record<string, never>, { userId: string }> {
server = new McpServer({ name: "docs", version: "1.0.0" });
async init() {
// The schema is the contract the calling model reads; keep it small and typed
this.server.tool(
"search_docs",
{ query: z.string().describe("Natural-language question"),
limit: z.number().int().min(1).max(20).default(5) },
async ({ query, limit }) => {
const [{ values }] = (await this.env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: [query],
})).data.map(v => ({ values: v }));
// The props carry the authenticated identity from the transport
const hits = await this.env.VECTORIZE.query(values, {
topK: limit,
returnMetadata: "all",
filter: { tenantId: { $eq: this.props.userId } },
});
return {
content: hits.matches.map(m => ({ type: "text" as const, text: m.metadata.text })),
};
},
);
}
}
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext) {
const { pathname } = new URL(req.url);
// Two transports, one agent; the SDK handles session state either way
if (pathname.startsWith("/sse")) return DocsMcp.serveSSE("/sse").fetch(req, env, ctx);
if (pathname === "/mcp") return DocsMcp.serve("/mcp").fetch(req, env, ctx);
return new Response("not found", { status: 404 });
},
};
Two controls turn this from a demo into something deployable. Tool scoping is the same argument as everywhere else: a tool that writes must check that this.props.userId is entitled to the write, because the calling model cannot be trusted to have honoured a permission it was told about in a description. Bounds are the other half: every tool that touches the index or the model takes a limit, every loop has an iteration ceiling, and the object’s state records how many tool calls the session has spent.
Complete Example Session
// ============================================
// PART 1: THE BINDINGS
// ============================================
// wrangler.jsonc
// "ai": { "binding": "AI" }
// "vectorize": [{ "binding": "VECTORIZE", "index_name": "docs" }]
// "durable_objects": { "bindings": [{ "name": "Support", "class_name": "Support" }] }
// "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Support"] }]
const EMBED_MODEL = "@cf/baai/bge-base-en-v1.5"; // 768 dimensions
const CHAT_MODEL = "@cf/meta/llama-3.1-8b-instruct";
// ============================================
// PART 2: THE INGEST PATH
// ============================================
async function ingest(env: Env, doc: Doc) {
const chunks = splitByHeading(doc.text, { maxTokens: 300, overlap: 40 });
const { data } = await env.AI.run(EMBED_MODEL, { text: chunks.map(c => c.text) });
await env.VECTORIZE.upsert(chunks.map((c, i) => ({
id: `${doc.id}#${i}`,
values: data[i],
metadata: { docId: doc.id, text: c.text, lang: doc.lang, year: doc.year },
namespace: "prod",
})));
}
// ============================================
// PART 3: THE EMBED OF THE QUESTION
// ============================================
async function embed(env: Env, question: string): Promise<number[]> {
// One string in, one vector out; the array shape is still returned
const { data } = await env.AI.run(EMBED_MODEL, { text: [question] });
return data[0];
}
// ============================================
// PART 4: THE RETRIEVAL
// ============================================
async function retrieve(env: Env, qvec: number[], lang: string) {
const hits = await env.VECTORIZE.query(qvec, {
topK: 8, // the ceiling with metadata returned
returnMetadata: "all",
namespace: "prod",
filter: { lang: { $eq: lang } }, // indexed property, runs pre-compare
});
return hits.matches.map(m => m.metadata.text);
}
// ============================================
// PART 5: THE PROMPT
// ============================================
function buildPrompt(question: string, context: string[]) {
return [
{ role: "system",
content: "Answer using only the context. If it is absent, say you do not know." },
{ role: "user", content: `Context:\n${context.join("\n---\n")}\n\nQ: ${question}` },
];
}
// ============================================
// PART 6: THE GATEWAY CALL
// ============================================
async function ask(env: Env, messages: any[], userId: string) {
return fetch(
`https://gateway.ai.cloudflare.com/v1/${env.ACCOUNT_ID}/${env.GATEWAY}/workers-ai/${CHAT_MODEL}`,
{
method: "POST",
headers: {
"content-type": "application/json",
"cf-aig-cache-ttl": "300", // reuse identical questions for 5 min
"cf-aig-metadata": JSON.stringify({ feature: "rag", userId }),
},
body: JSON.stringify({ messages, max_tokens: 400, stream: true }),
},
);
}
// ============================================
// PART 7: THE ENDPOINT
// ============================================
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext) {
const { question, lang = "en" } = await req.json<{ question: string; lang?: string }>();
const qvec = await embed(env, question);
const context = await retrieve(env, qvec, lang);
// The stream is returned without buffering, so tokens arrive immediately
return ask(env, buildPrompt(question, context), "anon");
},
};
// ============================================
// PART 8: THE AGENT SHELL
// ============================================
export class Support extends Agent<Env, { turns: number }> {
initialState = { turns: 0 };
async onMessage(conn: Connection, raw: string) {
const { question } = JSON.parse(raw);
const qvec = await embed(this.env, question);
const context = await retrieve(this.env, qvec, "en");
const res = await ask(this.env, buildPrompt(question, context), "session");
// Stream the gateway response straight down the socket
for await (const part of parseSSE(res.body!)) conn.send(part);
this.setState({ turns: this.state.turns + 1 });
}
}
// ============================================
// PART 9: THE MCP TOOL
// ============================================
this.server.tool(
"search_docs",
{ query: z.string(), limit: z.number().int().min(1).max(20).default(5) },
async ({ query, limit }) => {
const qvec = await embed(this.env, query);
const hits = await this.env.VECTORIZE.query(qvec, {
topK: limit,
returnMetadata: "all",
filter: { tenantId: { $eq: this.props.userId } }, // scoped per caller
});
return { content: hits.matches.map(m => ({ type: "text" as const, text: m.metadata.text })) };
},
);
// ============================================
// PART 10: THE COST GUARD
// ============================================
const MAX_TOOL_CALLS = 12;
if (this.state.turns >= MAX_TOOL_CALLS) {
return { content: [{ type: "text" as const, text: "call limit reached" }], isError: true };
}
The ten parts covered the bindings and the model constants, the ingest path with a batched embed and a namespaced upsert, the question embedding, the filtered retrieval, the prompt that constrains the model to the context, the gateway call with cache and metadata headers, the stateless endpoint, the agent shell that streams over a socket, the scoped MCP tool, and the call ceiling that keeps a tool loop from becoming a bill.
Quick Reference
The Four Products
| Product | State | Address | Billed On |
|---|---|---|---|
| Workers AI | Stateless | env.AI binding | Neurons |
| Vectorize | Persistent index | env.VECTORIZE binding | Stored + queried dimensions |
| AI Gateway | Config | gateway.ai.cloudflare.com URL | Plan tier |
| Agents | Per-object | routeAgentRequest / serve | DO requests + duration |
Embedding Models and Dimensions
| Model | Dimensions | Use |
|---|---|---|
@cf/baai/bge-small-en-v1.5 | 384 | Cheap, high volume |
@cf/baai/bge-base-en-v1.5 | 768 | Default for RAG |
@cf/baai/bge-large-en-v1.5 | 1024 | Accuracy over cost |
@cf/baai/bge-m3 | 1024 | Multilingual, long input |
Vectorize Query Options
| Option | Values | Effect |
|---|---|---|
topK | ≤ 20 with metadata | Candidates returned |
returnMetadata | none, indexed, all | Fields on the match |
filter | $eq, $in, $gte, … | Pre-compare predicate |
namespace | string | Coarse partition |
returnValues | boolean | Include the vector |
AI Gateway Headers
| Header | Purpose |
|---|---|
cf-aig-cache-ttl | Cache this response for N seconds |
cf-aig-skip-cache | Bypass a stored entry |
cf-aig-cache-key | Override the derived cache key |
cf-aig-metadata | JSON stored with the log entry |
cf-aig-cache-status | Response header: HIT or MISS |
MCP Transports
| Path | Transport | Client |
|---|---|---|
/sse | Server-Sent Events | Older MCP clients |
/mcp | Streamable HTTP | Current clients |
McpAgent.serveSSE(path) | Wires the SSE transport | — |
McpAgent.serve(path) | Wires streamable HTTP | — |
Best Practices
✅ Do This:
// Batch the embeddings in one call
await env.AI.run(EMBED_MODEL, { text: chunks.map(c => c.text) }); // ✅
// Put the model id next to the index name
const EMBED_MODEL = "@cf/baai/bge-base-en-v1.5"; // 768, matches the index ✅
// Cap the output explicitly
{ max_tokens: 400, temperature: 0.2 } // ✅
// Filter on an indexed property, in the query
filter: { lang: { $eq: "en" } } // ✅
// Cache only non-personal answers
{ "cf-aig-cache-ttl": "300" } // ✅
// Tag the log so it can be filtered later
{ "cf-aig-metadata": JSON.stringify({ feature, userId }) } // ✅
// Scope each MCP tool to the calling identity
filter: { tenantId: { $eq: this.props.userId } } // ✅
// Bound the tool loop
if (this.state.turns >= MAX_TOOL_CALLS) return error; // ✅
❌ Don’t Do This:
// One embedding call per chunk
for (const c of chunks) await env.AI.run(EMBED_MODEL, { text: [c] }); // ❌
// An index at 768 fed by a 1024 model
new VectorizeIndex({ dimensions: 768 }); // + bge-m3 embeddings // ❌
// No cap, no temperature
await env.AI.run(CHAT_MODEL, { messages }); // ❌
// Filtering on an unindexed property
filter: { author: { $eq: "x" } } // no metadata index // ❌
// Caching a personalised answer
{ "cf-aig-cache-ttl": "3600" } // per-user content // ❌
// A tool that trusts the model to have checked permissions
async ({ id }) => deleteDoc(this.env, id); // ❌
// An unbounded tool loop
while (needsMore) await callTool(); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Dimension mismatch on upsert | Model changed, index did not | Pin the model id next to the index |
| Filter matches nothing | Property has no metadata index | create-metadata-index |
| Retrieval misses the answer | Chunk too small or too large | 200–400 tokens, overlap 10–20% |
| Answers hallucinate sources | Context not constrained | Instruct “only the context” |
| Stale cached answer | TTL longer than content life | Short TTL, skip-cache for fresh |
| Every request a cache miss | Body contains a timestamp | cf-aig-cache-key |
| Slow first token | Cold model, no streaming | Stream, pick a smaller model |
| Agent loops on one tool | No call ceiling | Bound by state counter |
| MCP tool reads another tenant | No identity scoping | this.props in the filter |
Real-World Examples
1. Bind the model
import { Agent, routeAgentRequest } from "agents";
2. Batch the embed
const { data } = await env.AI.run(EMBED_MODEL, { text: batch });
3. Create the index
wrangler vectorize create docs --dimensions=768 --metric=cosine
4. Index the filter property
wrangler vectorize create-metadata-index docs --property-name=lang --type=string
5. Namespaced upsert
await env.VECTORIZE.upsert([{ id, values, metadata, namespace: "prod" }]);
6. Filtered query
await env.VECTORIZE.query(vec, { topK: 8, filter: { lang: { $eq: "en" } } });
7. Gateway cache
headers: { "cf-aig-cache-ttl": "300" }
8. Gateway metadata
headers: { "cf-aig-metadata": JSON.stringify({ feature: "rag" }) }
9. Fallback chain
body: JSON.stringify([{ provider: "workers-ai", endpoint: A }, { provider: "workers-ai", endpoint: B }])
10. MCP tool
this.server.tool("search_docs", { query: z.string() }, handler);
Visual
The Four Layers
┌────────────────────────────────────────────────────────┐
│ THE FOUR LAYERS │
│ │
│ Workers AI run a model, get a result │
│ Vectorize store and search embeddings │
│ AI Gateway route, cache, log, rate-limit │
│ Agents stateful orchestration over both │
│ │
│ A RAG request uses all four: embed the question, │
│ search the index, prompt the model, log the call. │
└────────────────────────────────────────────────────────┘
The RAG Path
┌────────────────────────────────────────────────────────┐
│ THE RAG PATH │
│ │
│ question ──► AI.run(bge) ──► 768-float vector │
│ │ │
│ ▼ │
│ VECTORIZE.query(vec, {topK, filter}) │
│ │ │
│ ▼ │
│ top-8 chunks with metadata │
│ │ │
│ ▼ │
│ prompt: system + context + question │
│ │ │
│ ▼ │
│ GATEWAY ──► AI.run(llama, {stream:true}) ──► tokens │
│ │
│ Two model calls, one index query, one gateway hop. │
└────────────────────────────────────────────────────────┘
Gateway Controls
┌────────────────────────────────────────────────────────┐
│ GATEWAY CONTROLS │
│ │
│ request ──► [cache] hit ──► stored response │
│ │ miss │
│ ▼ │
│ [limit] over ──► 429 │
│ │ under │
│ ▼ │
│ [primary] fail ──► [fallback] │
│ │ success │
│ ▼ │
│ [log] request, response, cost, metadata │
│ │
│ The caller changes one base URL and nothing else. │
└────────────────────────────────────────────────────────┘
Agent and MCP
┌────────────────────────────────────────────────────────┐
│ AGENT AND MCP │
│ │
│ /agents/support/alice ──► Support("alice") │
│ ├── state (transcript) │
│ ├── SQLite │
│ ├── WebSockets (hibernate)│
│ └── schedule() │
│ │
│ /mcp ──► DocsMcp (stateless request/response) │
│ ├── tool: search_docs │
│ ├── props: { userId } ← auth context │
│ └── env: AI, VECTORIZE │
│ │
│ One object per conversation; one tool surface per │
│ client. State is the difference between a chat and │
│ a series of unrelated prompts. │
└────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Inference binding | env.AI.run(model, inputs) |
| Chat response field | { response } |
| Embedding response field | { data }, one vector per input |
| Streaming flag | stream: true, returns ReadableStream |
| Billing unit | Neurons; free 10,000/day |
| Index immutables | Dimensions and metric |
| Metadata filters | Require a metadata index |
topK ceiling | 20 with metadata, 100 ids-only |
| Gateway URL | gateway.ai.cloudflare.com/v1/{acct}/{gw}/{provider} |
| Gateway cache header | cf-aig-cache-ttl |
| Agent backing | Durable Object with SQLite |
| MCP transports | /sse and /mcp |
Key takeaways:
- The model id and the index dimensions are one decision, not two. A 768-dimension index fed by a 1024-dimension model fails at write time with an error that reads like a schema problem. Keep the constant next to the index name and assert the length on insert.
- Batch the embeddings. One
textarray of forty chunks is one call and forty vectors; forty calls is forty round trips and forty times the fixed overhead. The same reasoning applies to ingest, to backfill, and to any script that walks a corpus. - Chunking decides whether retrieval works. 200–400 tokens with overlap, split on structural boundaries, metadata carrying the parent id and the text. A chunk too small splits a fact; a chunk too large buries it; neither failure looks like a chunking problem from the outside.
- Filter before comparing, and index the property first. A metadata filter on an unindexed property matches nothing or errors, and the symptom is indistinguishable from bad retrieval until you look.
create-metadata-indexis a prerequisite, not a tuning step. - AI Gateway is a URL, so it composes with everything. It caches on the request body, limits on a key you choose, falls back through an array of provider entries, and logs the cost with whatever metadata you attached. The caller changes one base URL and keeps every other line of code.
- Cache non-personal answers only, and short. A cached RAG response outlives the document it summarised, and a per-user cache is a data leak with a TTL.
cf-aig-skip-cacheon anything personal or time-sensitive,cf-aig-cache-ttlin seconds on everything else. - An Agent is a Durable Object, which is why the conversation is stateful at all. State broadcasts to every connected socket, SQLite is available for what state does not fit, and
schedulesurvives a redeploy. That is the difference between a chat and a series of unrelated prompts. - An MCP tool needs scoping and bounds.
this.propscarries the identity; the filter must use it; every tool that touches the index takes alimit; and the call ceiling lives in state so a loop terminates before the invoice arrives.
Remember: The four products are arranged in a dependency order that mirrors the request: embed, search, prompt, stream, log. Workers AI produces the vector and the answer, Vectorize holds the vectors and answers the nearest-neighbour query, AI Gateway wraps every model call with the cache and the limit and the log, and Agents makes the whole thing stateful per conversation and exposes it to other clients over MCP. Each layer has one thing it cannot do — Workers AI remembers nothing, Vectorize generates nothing, the Gateway is not a runtime, and an Agent is not a place to run a model — and the architecture works precisely because none of them tries.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!