Build a Retrieval Augmented Generation (RAG) AI

Last updated Aug 25, 2026 This guide will instruct you through setting up and deploying your first application with Cloudflare AI. You will build a fully-featured AI-powered application, using tools like Workers AI, Vectorize, D1, and Cloudflare Workers.

Looking for a managed option?

AI Search offers a fully managed way to build RAG pipelines on Cloudflare, handling ingestion, indexing, and querying out of the box. Get started.

At the end of this tutorial, you will have built an AI tool that allows you to store information and query it using a Large Language Model. This pattern, known as Retrieval Augmented Generation, or RAG, is a useful project you can build by combining multiple aspects of Cloudflare's AI toolkit. You do not need to have experience working with AI tools to build this application.

  1. Sign up for a Cloudflare account ↗︎.
  2. Install Node.js ↗︎.

<details>

<summary>

Node.js version manager

</summary>

Use <a href="https://viteplus.dev/guide/env">Vite+ (<code>vp env</code>) ↗︎</a> to install and manage Node.js versions.

For supported Node.js versions, refer to the <a href="https://developers.cloudflare.com/workers/wrangler/install-and-update/#install-wrangler">Wrangler system requirements</a>.

</details>

You will also need access to Vectorize. During this tutorial, we will show how you can optionally integrate with Anthropic Claude ↗︎ as well. You will need an Anthropic API key ↗︎ to do so.

1. Create a new Worker project

C3 (create-cloudflare-cli) is a command-line tool designed to help you setup and deploy Workers to Cloudflare as fast as possible.

Open a terminal window and run C3 to create your Worker project:

npmyarnpnpm

npm create cloudflare@latest -- rag-ai-tutorial
yarn create cloudflare rag-ai-tutorial
pnpm create cloudflare@latest rag-ai-tutorial

For setup, select the following options:

  • For What would you like to start with?, choose Hello World example.
  • For Which template would you like to use?, choose Worker only.
  • For Which language do you want to use?, choose JavaScript.
  • For Do you want to use git for version control?, choose Yes.
  • For Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?, choose Yes.
  • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).

In your project directory, C3 has generated several files.

<details>

<summary>

What files did C3 create?

</summary>

  1. <code>wrangler.jsonc</code>: Your <a href="https://developers.cloudflare.com/workers/wrangler/configuration/#sample-wrangler-configuration">Wrangler</a> configuration file.
  2. <code>index.js</code> (in <code>/src</code>): A minimal <code>'Hello World!'</code> Worker written in <a href="https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/">ES module</a> syntax.
  3. <code>package.json</code>: A minimal Node dependencies configuration file.
  4. <code>package-lock.json</code>: Refer to <a href="https://docs.npmjs.com/cli/v9/configuring-npm/package-lock-json"><code>npm</code> documentation on <code>package-lock.json</code> ↗︎</a>.
  5. <code>node_modules</code>: Refer to <a href="https://docs.npmjs.com/cli/v7/configuring-npm/folders#node-modules"><code>npm</code> documentation <code>node_modules</code> ↗︎</a>.

</details>

Now, move into your newly created directory:

cd rag-ai-tutorial

2. Develop with Wrangler CLI

The Workers command-line interface, Wrangler, allows you to create, test, and deploy your Workers projects. C3 will install Wrangler in projects by default.

After you have created your first Worker, run the wrangler dev command in the project directory to start a local server for developing your Worker. This will allow you to test your Worker locally during development.

npx wrangler dev

You will now be able to go to http://localhost:8787 ↗︎ to see your Worker running. Any changes you make to your code will trigger a rebuild, and reloading the page will show you the up-to-date output of your Worker.

3. Adding the AI binding

To begin using Cloudflare's AI products, you can add the ai block to the Wrangler configuration file as a remote binding. This will set up a binding to Cloudflare's AI models in your code that you can use to interact with the available AI models on the platform.

Note

If you have not used Wrangler before, it will try to open your web browser to login with your Cloudflare account.

If you have issues with this step or you do not have access to a browser interface, refer to the wrangler login documentation for more information.

This example features the @cf/meta/llama-3-8b-instruct model, which generates text.

{
    "ai": {
        "binding": "AI",
        "remote": true
    }
}
[ai]
binding = "AI"
remote = true

Now, find the src/index.js file. Inside the fetch handler, you can query the AI binding:

export default {
    async fetch(request, env, ctx) {
        const answer = await env.AI.run("@cf/meta/llama-3-8b-instruct", {
            messages: [{ role: "user", content: `What is the square root of 9?` }],
        });

return new Response(JSON.stringify(answer));
    },
};

By querying the LLM through the AI binding, we can interact directly with Cloudflare AI's large language models directly in our code. In this example, we are using the @cf/meta/llama-3-8b-instruct model, which generates text.

Deploy your Worker using wrangler:

npx wrangler deploy

Making a request to your Worker will now generate a text response from the LLM, and return it as a JSON object.

curl https://example.username.workers.dev
{"response":"Answer: The square root of 9 is 3."}

4. Adding embeddings using Cloudflare D1 and Vectorize

Embeddings allow you to add additional capabilities to the language models you can use in your Cloudflare AI projects. This is done via Vectorize, Cloudflare's vector database.

To begin using Vectorize, create a new embeddings index using wrangler. This index will store vectors with 768 dimensions, and will use cosine similarity to determine which vectors are most similar to each other:

npx wrangler vectorize create vector-index --dimensions=768 --metric=cosine

Then, add the configuration details for your new Vectorize index to the Wrangler configuration file:

{
    // ... existing wrangler configuration
    "vectorize": [
        {
            "binding": "VECTOR_INDEX",
            "index_name": "vector-index"
        }
    ]
}
[[vectorize]]
binding = "VECTOR_INDEX"
index_name = "vector-index"

A vector index allows you to store a collection of dimensions, which are floating point numbers used to represent your data. When you want to query the vector database, you can also convert your query into dimensions. Vectorize is designed to efficiently determine which stored vectors are most similar to your query.

To implement the searching feature, you must set up a D1 database from Cloudflare. In D1, you can store your app's data. Then, you change this data into a vector format. When someone searches and it matches the vector, you can show them the matching data.

Create a new D1 database using wrangler:

npx wrangler d1 create database

Then, paste the configuration details output from the previous command into the Wrangler configuration file:

{
    // ... existing wrangler configuration
    "d1_databases": [
        {
            "binding": "DB", // available in your Worker on env.DB
            "database_name": "database",
            "database_id": "abc-def-geh" // replace this with a real database_id (UUID)
        }
    ]
}
[[d1_databases]]
binding = "DB"
database_name = "database"
database_id = "abc-def-geh"

In this application, we'll create a notes table in D1, which will allow us to store notes and later retrieve them in Vectorize. To create this table, run a SQL command using wrangler d1 execute:

npx wrangler d1 execute database --remote --command "CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)"

Now, we can add a new note to our database using wrangler d1 execute:

npx wrangler d1 execute database --remote --command "INSERT INTO notes (text) VALUES ('The best pizza topping is pepperoni')"

5. Creating a workflow

Before we begin creating notes, we will introduce a Cloudflare Workflow. This will allow us to define a durable workflow that can safely and robustly execute all the steps of the RAG process.

To begin, add a new [[workflows]] block to your Wrangler configuration file:

{
    // ... existing wrangler configuration
    "workflows": [
        {
            "name": "rag",
            "binding": "RAG_WORKFLOW",
            "class_name": "RAGWorkflow"
        }
    ]
}
[[workflows]]
name = "rag"
binding = "RAG_WORKFLOW"
class_name = "RAGWorkflow"

In src/index.js, add a new class called RAGWorkflow that extends WorkflowEntrypoint:

import { WorkflowEntrypoint } from "cloudflare:workers";

export class RAGWorkflow extends WorkflowEntrypoint {
    async run(event, step) {
        await step.do("example step", async () => {
            console.log("Hello World!");
        });
    }
}

This class will define a single workflow step that will log "Hello World!" to the console. You can add as many steps as you need to your workflow.

On its own, this workflow will not do anything. To execute the workflow, we will call the RAG_WORKFLOW binding, passing in any parameters that the workflow needs to properly complete. Here is an example of how we can call the workflow:

env.RAG_WORKFLOW.create({ params: { text } });

6. Creating notes and adding them to Vectorize

To expand on your Workers function in order to handle multiple routes, we will add hono, a routing library for Workers. This will allow us to create a new route for adding notes to our database. Install hono using npm:

npmyarnpnpmbun

npm i hono
yarn add hono
pnpm add hono
bun add hono

Then, import hono into your src/index.js file. You should also update the fetch handler to use hono:

import { Hono } from "hono";
const app = new Hono();

app.get("/", async (c) => {
    const answer = await c.env.AI.run("@cf/meta/llama-3-8b-instruct", {
        messages: [{ role: "user", content: `What is the square root of 9?` }],
    });

return c.json(answer);
});

export default app;

This will establish a route at the root path / that is functionally equivalent to the previous version of your application.

Now, we can update our workflow to begin adding notes to our database, and generating the related embeddings for them.

This example features the @cf/baai/bge-base-en-v1.5 model, which can be used to create an embedding. Embeddings are stored and retrieved inside Vectorize, Cloudflare's vector database. The user query is also turned into an embedding so that it can be used for searching within Vectorize.

import { WorkflowEntrypoint } from "cloudflare:workers";

export class RAGWorkflow extends WorkflowEntrypoint {
    async run(event, step) {
        const env = this.env;
        const { text } = event.payload;

const record = await step.do(`create database record`, async () => {
            const query = "INSERT INTO notes (text) VALUES (?) RETURNING *";

const { results } = await env.DB.prepare(query).bind(text).run();

const record = results[0];
            if (!record) throw new Error("Failed to create note");
            return record;
        });

const embedding = await step.do(`generate embedding`, async () => {
            const embeddings = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
                text: text,
            });
            const values = embeddings.data[0];
            if (!values) throw new Error("Failed to generate vector embedding");
            return values;
        });

await step.do(`insert vector`, async () => {
            return env.VECTOR_INDEX.upsert([
                {
                    id: record.id.toString(),
                    values: embedding,
                },
            ]);
        });
    }
}

The workflow does the following things:

  1. Accepts a text parameter.
  2. Insert a new row into the notes table in D1, and retrieve the id of the new row.
  3. Convert the text into a vector using the embeddings model of the LLM binding.
  4. Upsert the id and vectors into the vector-index index in Vectorize.