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.
- Sign up for a Cloudflare account ↗.
- 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.
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 yarn create cloudflare ai-search-tutorial pnpm create cloudflare@latest ai-search-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
TypeScript. - For Do you want to use git for version control?, choose
Yes. - For Do you want to deploy your application?, choose
No(we will be making some changes before deploying).
Go to your application directory:
cd ai-search-tutorialCreate 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 = trueThis 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.
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.
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); },};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>;Start a local development server:
npx wrangler devWrangler 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.
Log in with your Cloudflare account:
npx wrangler loginDeploy your Worker to make it accessible on the Internet:
npx wrangler deployhttps://ai-search-tutorial.<YOUR_SUBDOMAIN>.workers.dev