Workers binding
import { Render, MetaInfo, Type } from "~/components";
Workers provides a serverless execution environment that allows you to create new applications or augment existing ones. Use a Workers binding to create, list, update, and delete AI Search instances from a Cloudflare Worker. You can also check instance configuration and monitor indexing progress.
Configure the binding
Namespace methods
The following methods are only available when using the ai_search_namespaces binding. The namespace handle (env.AI_SEARCH) exposes methods for working with instances within a namespace.
get()
Returns a handle to a specific instance. This is synchronous and does not make a network call. The instance is resolved lazily when you call methods like search() or info().
const instance = env.AI_SEARCH.get("my-instance");
const results = await instance.search({
messages: [{ role: "user", content: "What is Cloudflare?" }],
});
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
name |
string | Yes | The name of the instance to get a handle to. |
list()
Returns all instances within the namespace.
const { result, result_info } = await env.AI_SEARCH.list();
for (const instance of result) {
console.log(`${instance.id} (${instance.type}) - ${instance.status}`);
}
// result_info.total_count contains the total number of instances
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
page |
number | No | The page number to return. Defaults to 1. |
per_page |
number | No | The number of instances per page. Defaults to 20. Maximum 100. |
search |
string | No | Search instances by ID. |
order_by |
string | No | Sort column. Valid value: created_at. Defaults to created_at. |
order_by_direction |
string | No | Sort direction. Valid values: asc, desc. Defaults to desc. |
Response
| Field | Type | Description |
|---|---|---|
result |
array | Array of instance objects. |
result[].id |
string | The instance identifier. |
result[].type |
string | The data source type (r2, web-crawler, or null for empty instances). |
result[].source |
string | The data source location. |
result[].status |
string | The current indexing lifecycle status, such as waiting, index_source, embed_files, or a paused_* status. |
result[].paused |
boolean | Whether indexing is paused. |
result[].namespace |
string | The namespace the instance belongs to. |
result[].created_at |
string | ISO 8601 timestamp of when the instance was created. |
result[].modified_at |
string | ISO 8601 timestamp of the last modification. |
result_info |
object | Pagination metadata. |
result_info.total_count |
number | Total number of instances in the namespace. |
create()
Creates a new instance and returns a handle to it. You can create instances backed by a data source or create empty instances for use with the Items API.
Create an empty instance for file uploads:
AI Search instances come with built-in storage where you can upload documents directly.
const instance = await env.AI_SEARCH.create({
id: "knowledge-base",
});
// Upload documents using the Items API
await instance.items.upload("guide.pdf", pdfBlob);
Create a web-crawler instance:
Automatically crawl and index a website that you own. For more configuration options, refer to Website data source.
const instance = await env.AI_SEARCH.create({
id: "my-docs",
type: "web-crawler",
source: "developers.cloudflare.com",
});
Create an R2-backed instance:
Index documents stored in an R2 bucket. For more configuration options, refer to R2 data source.
const instance = await env.AI_SEARCH.create({
id: "internal-docs",
type: "r2",
source: "my-docs-bucket",
});
Parameters
Response
Returns an AiSearchInstance handle that is immediately usable for calling methods like search(), info(), stats(), and items.upload(). Call info() on the handle to get the instance configuration.
delete()
Permanently deletes an instance and all its indexed content. This action cannot be undone.
await env.AI_SEARCH.delete("old-docs");
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
name |
string | Yes | The name of the instance to delete. |
Response
Returns void. Throws an error if the instance does not exist.
:::caution Deleting an instance permanently removes all indexed data, including embeddings, chunks, and source files. :::
Instance methods
The following methods are available on both the ai_search_namespaces and ai_search bindings. With the namespace binding, call methods on the handle returned by get(). With the instance binding, call methods directly on the binding (for example, env.MY_SEARCH.info()).
The examples below use the namespace binding.
update()
Partially updates the instance configuration. Only the fields you pass are modified.
const updated = await env.AI_SEARCH.get("my-instance").update({
ai_search_model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
reranking: true,
});
Parameters
Accepts a partial version of the create parameters. Only the fields you include are updated.
| Field | Type | Description |
|---|---|---|
ai_search_model |
string | The text-generation model. |
embedding_model |
string | The embedding model. |
index_method |
object | Indexing methods: \{ vector: boolean, keyword: boolean \}. |
fusion_method |
string | How vector and keyword scores are combined (rrf or max). |
indexing_options |
object | Indexing configuration including keyword_tokenizer and use_ocr. |
retrieval_options |
object | Retrieval configuration including keyword_match_mode and boost_by. |
reranking |
boolean | Turn on or off reranking. |
reranking_model |
string | The reranking model. |
rewrite_query |
boolean | Turn on or off query rewriting. |
rewrite_model |
string | The query rewriting model. |
source |
string | Update the data source location. |
cache |
boolean | Turn on or off response caching. |
cache_ttl |
number | Cache entry time to live in seconds. |
chunk_size |
number | Token size of each chunk. |
chunk_overlap |
number | Token overlap between chunks. |
score_threshold |
number | Minimum score threshold for results. |
max_num_results |
number | Maximum number of results per query. |
custom_metadata |
array | Custom metadata field definitions. |
sync_interval |
number | Seconds between automatic data source syncs. |
Response
Returns the updated instance configuration. Same shape as info().
info()
Returns the current configuration and metadata for the instance.
const info = await env.AI_SEARCH.get("my-instance").info();
Response
| Field | Type | Description |
|---|---|---|
id |
string | The instance identifier. |
type |
string | The data source type (r2, web-crawler, or null). |
source |
string | The data source location. |
namespace |
string | The namespace the instance belongs to. |
status |
string | The current indexing lifecycle status, such as waiting, index_source, embed_files, or a paused_* status. |
paused |
boolean | Whether indexing is paused. |
created_at |
string | Timestamp of when the instance was created. |
modified_at |
string | Timestamp of the last modification. |
ai_search_model |
string | The text-generation model. |
embedding_model |
string | The embedding model. |
reranking |
boolean | Whether reranking is enabled. |
reranking_model |
string | The reranking model. |
rewrite_query |
boolean | Whether query rewriting is enabled. |
rewrite_model |
string | The query rewriting model. |
cache |
boolean | Whether response caching is enabled. |
cache_threshold |
string | The similarity threshold for cache hits. |
cache_ttl |
number | Cache entry time to live in seconds. |
index_method |
object | Which indexing methods are enabled (vector, keyword). |
fusion_method |
string | How vector and keyword scores are combined (rrf or max). |
indexing_options |
object | Indexing configuration including keyword_tokenizer and use_ocr. |
retrieval_options |
object | Retrieval configuration including keyword_match_mode and boost_by. |
chunk_size |
number | Token size of each chunk. |
chunk_overlap |
number | Token overlap between chunks. |
score_threshold |
number | Minimum score threshold for results. |
max_num_results |
number | Maximum number of results per query. |
sync_interval |
number | Seconds between automatic data source syncs. |
custom_metadata |
array | Custom metadata field definitions. |
last_activity |
string | Timestamp of the last indexing activity. |
stats()
Returns the current indexing progress for the instance. Use this to poll for completion after creating an instance or uploading files.
const stats = await env.AI_SEARCH.get("my-instance").stats();
Response
| Field | Type | Description |
|---|---|---|
queued |
number | Items waiting to be processed. |
running |
number | Items currently being processed. |
completed |
number | Items successfully indexed. |
error |
number | Items that failed to index. |
skipped |
number | Items skipped during indexing. |
outdated |
number | Items that need re-indexing. |
last_activity |
string | ISO 8601 timestamp of the last indexing activity. |
file_embed_errors |
object | Map of file IDs to embedding error details. |
engine.vectorize.vectorsCount |
number | Total number of vectors stored. |
engine.vectorize.dimensions |
number | Dimensions of the vector embeddings. |
engine.r2.payloadSizeBytes |
number | Total size of stored payloads in bytes. |
engine.r2.metadataSizeBytes |
number | Total size of stored metadata in bytes. |
engine.r2.objectCount |
number | Total number of objects in storage. |
Jobs methods
Use the jobs property on an instance handle to manage indexing jobs.
jobs.list()
Returns a paginated list of jobs. Pass optional page and per_page values.
const jobs = await env.AI_SEARCH.get("my-instance").jobs.list({
page: 1,
per_page: 20,
});
jobs.create()
Starts an indexing job. The optional description can contain up to 255 characters.
const job = await env.AI_SEARCH.get("my-instance").jobs.create({
description: "Index updated content",
});
jobs.get().info()
Returns one job by ID.
const job = await env.AI_SEARCH.get("my-instance")
.jobs.get("job-id-123")
.info();
Job objects contain id, source, and optional description, last_seen_at, started_at, ended_at, and end_reason fields. The source is user or schedule.
jobs.get().cancel()
Cancels a job and returns the updated job object.
const job = await env.AI_SEARCH.get("my-instance")
.jobs.get("job-id-123")
.cancel();
jobs.get().logs()
Returns paginated logs for a job. Pass optional page and per_page values.
const logs = await env.AI_SEARCH.get("my-instance")
.jobs.get("job-id-123")
.logs({ page: 1, per_page: 20 });
Each log contains id, message, message_type, and created_at. The response includes result_info pagination metadata.
:::note The configured AI Gateway receives generation, query rewriting, and external-provider requests. Workers AI embedding and reranking requests run under AI Search and do not appear in your AI Gateway logs or Workers AI bill. :::
Local development
Local development is supported by proxying requests to your deployed AI Search instance. Add remote: true to your binding configuration to enable local development with wrangler dev.
// wrangler.jsonc
{
"ai_search": [
{
"binding": "MY_SEARCH",
"instance_name": "my-instance",
"remote": true,
},
],
}
谢谢你的反馈!