INTEGRITY Cloudflare Docs

Workers binding

This guide walks you through creating and querying an AI Search instance from a Cloudflare Worker using the Workers Binding. The Workers Binding uses a runtime API that runs inside a Worker and calls AI Search without managing API tokens.

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

Node.js version manager

Use a Node version manager like Volta or nvm to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.

1. Create a Worker project

Create a new Worker project using the create-cloudflare CLI (C3). C3 is a command-line tool designed to help you set up and deploy new applications to Cloudflare.

Create a new project named ai-search-tutorial by running:

npm create cloudflare@latest -- ai-search-tutorial

For setup, select the following options:

Go to your application directory:

cd ai-search-tutorial

Create a binding between your Worker and your AI Search instance. Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform.

Add the following to your Wrangler configuration file:

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "ai_search_namespaces": [
    {
      "binding": "AI_SEARCH",
      "namespace": "default",
      "remote": true
    }
  ]
}
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true

This binds the default namespace to env.AI_SEARCH. Instances that you create without specifying a namespace belong to the default namespace. The remote option lets wrangler dev proxy requests to your deployed instance, since AI Search does not run locally. For all binding options, refer to the Workers binding reference.

3. Create and query AI Search from your Worker

Update the src/index.ts file in your ai-search-tutorial directory with the following code. It exposes two routes: /setup creates an instance named my-instance and indexes a sample document, and the default route queries it.

src/index.js
export default {
	async fetch(request, env) {
		const url = new URL(request.url);

		// Visit /setup once to create an instance and index a sample document.
		if (url.pathname === "/setup") {
			const instance = await env.AI_SEARCH.create({ id: "my-instance" });
			const item = await instance.items.uploadAndPoll(
				"getting-started.md",
				"AI Search indexes uploaded content for retrieval.",
			);
			return Response.json({ created: "my-instance", status: item.status });
		}

		// Query the instance.
		const query = url.searchParams.get("q") ?? "What does AI Search do?";

		const results = await env.AI_SEARCH.get("my-instance").search({
			messages: [{ role: "user", content: query }],
			ai_search_options: {
				retrieval: { max_num_results: 3 },
			},
		});

		return Response.json(results.chunks);
	},
};
src/index.ts
export interface Env {
	AI_SEARCH: AiSearchNamespace;
}

export default {
	async fetch(request, env): Promise<Response> {
		const url = new URL(request.url);

		// Visit /setup once to create an instance and index a sample document.
		if (url.pathname === "/setup") {
			const instance = await env.AI_SEARCH.create({ id: "my-instance" });
			const item = await instance.items.uploadAndPoll(
				"getting-started.md",
				"AI Search indexes uploaded content for retrieval.",
			);
			return Response.json({ created: "my-instance", status: item.status });
		}

		// Query the instance.
		const query = url.searchParams.get("q") ?? "What does AI Search do?";

		const results = await env.AI_SEARCH.get("my-instance").search({
			messages: [{ role: "user", content: query }],
			ai_search_options: {
				retrieval: { max_num_results: 3 },
			},
		});

		return Response.json(results.chunks);
	},
} satisfies ExportedHandler<Env>;

4. Develop locally

Start a local development server:

npx wrangler dev

Wrangler gives you a URL (usually localhost:8787). Visit /setup once to create your instance and index the sample document, then query it at /?q=your+search+terms.

5. Deploy your Worker

Log in with your Cloudflare account:

npx wrangler login

Deploy your Worker to make it accessible on the Internet:

npx wrangler deploy
https://ai-search-tutorial.<YOUR_SUBDOMAIN>.workers.dev

Next steps

Search Workers binding

Full reference for searching and chatting from a Worker.

Items Workers binding

Upload, list, and manage documents from a Worker.