Workers binding (5)
Last updated Oct 1, 2026 provides a serverless execution environment that allows you to create new applications or augment existing ones. Use a Workers binding to search and chat with your AI Search instances from a Cloudflare Worker.
Configure the binding
To use AI Search with Workers, you must create an AI Search binding. You create bindings by updating your Wrangler configuration. AI Search provides two types of bindings:
- Namespace binding:
ai_search_namespaces - Instance binding:
ai_search
Namespace binding
Access all instances within a namespace. You can get, create, list, and delete instances at runtime.
{
"$schema": "./node_modules/wrangler/config-schema.json",
"compatibility_date": "2026-03-27",
"ai_search_namespaces": [
{
"binding": "AI_SEARCH",
"namespace": "my-namespace"
}
]
}
compatibility_date = "2026-03-27"
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "my-namespace"
| Field | Type | Required | Description |
|---|---|---|---|
binding |
string | Yes | The variable name available on env. For example, "AI_SEARCH" makes it accessible as env.AI_SEARCH. |
namespace |
string | Yes | The namespace to bind to. A default namespace is created automatically for every account. If the namespace does not exist, Wrangler creates it on deploy. |
remote |
boolean | No | Set to true for local development with wrangler dev. |
Instance binding
Bind directly to a single instance in the default namespace. Use this when you know which instance you need at deploy time.
{
"$schema": "./node_modules/wrangler/config-schema.json",
"compatibility_date": "2026-03-27",
"ai_search": [
{
"binding": "MY_SEARCH",
"instance_name": "my-instance"
}
]
}
compatibility_date = "2026-03-27"
[[ai_search]]
binding = "MY_SEARCH"
instance_name = "my-instance"
| Field | Type | Required | Description |
|---|---|---|---|
binding |
string | Yes | The variable name available on env. For example, "MY_SEARCH" makes it accessible as env.MY_SEARCH. |
instance_name |
string | Yes | The name of the AI Search instance. Must exist in the default namespace at deploy time. |
remote |
boolean | No | Set to true for local development with wrangler dev. |
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.search()).
The examples below use the namespace binding.
search()
Search for relevant content chunks from your indexed data source. Returns scored chunks with source references.
const instance = env.AI_SEARCH.get("my-instance");
const results = await instance.search({
messages: [{ role: "user", content: "What is Cloudflare?" }],
});
Parameters
The Workers binding accepts string values for messages[].content. To send image or file content parts, use the REST API or a public endpoint.
messages array required
An array of message objects representing the conversation. Each message has a role and content field.
rolestringrequired- The role of the message sender. Valid values:
system,developer,user,assistant,tool. contentstring | arrayrequired- The message content. Use a string for text, or an array containing
text,image_url, andfileparts. - A
textpart containstext. Animage_urlpart contains anhttps://URL or adata:image/<subtype>;base64,...URI. - A
filepart containsfile_dataas adata:<mime>;base64,...URI and afilename. The decoded file can be up to 10 MiB.
query string optional
A simple text query string. Alternative to messages. Provide either query or messages, not both.
ai_search_options object optional
Configuration options for the search operation.
custom_metadataobjectoptional- Adds up to two string, number, or boolean entries to AI Gateway logs. The keys
ai-search,task,origin, and keys beginning withcf.are reserved. retrievalobjectoptionalretrieval_typestringoptional- The type of retrieval to perform. Valid values:
vector,keyword,hybrid. Defaults tohybrid.
- The type of retrieval to perform. Valid values:
match_thresholdnumberoptional- The minimum match score required for a result to be considered a match. Must be between
0and1. Defaults to0.4.
- The minimum match score required for a result to be considered a match. Must be between
max_num_resultsintegeroptional- The maximum number of results to return. Must be between
1and50. Defaults to10.
- The maximum number of results to return. Must be between
filtersobjectoptional- Filter search results based on metadata. Supports comparison filters (
eq,ne,gt,gte,lt,lte) and compound filters (and,or). For more details, refer to Metadata filtering.
- Filter search results based on metadata. Supports comparison filters (
context_expansionintegeroptional- The number of surrounding chunks to include for additional context. Must be between
0and3. Defaults to0.
- The number of surrounding chunks to include for additional context. Must be between
fusion_methodstringoptional- Controls how vector and keyword scores are combined when using hybrid retrieval. Valid values:
rrf(Reciprocal Rank Fusion),max(takes the maximum score). Defaults to the instance-level setting.
- Controls how vector and keyword scores are combined when using hybrid retrieval. Valid values:
keyword_match_modestringoptional- Controls how keyword (BM25) matching selects candidate documents.
andrequires all terms to match.orrequires any term to match. Defaults toand.
- Controls how keyword (BM25) matching selects candidate documents.
boost_byarrayoptional- Boost results by metadata fields. Maximum 3 items. Each item has:
fieldstringrequired - The metadata field name to boost by (for example,timestamp). Maximum 64 characters.directionstringoptional - The boost direction. Valid values:asc,desc,exists,not_exists. Defaults toascfor numeric fields andexistsfor text fields.
metadata_onlybooleanoptional- Return only metadata for each chunk without the text content.
return_on_failurebooleanoptional- Whether to return partial results if some processing steps fail. Defaults to
true.
- Whether to return partial results if some processing steps fail. Defaults to
query_rewriteobjectoptionalenabledbooleanoptional- Rewrites the query to improve retrieval accuracy. Defaults to
false.
- Rewrites the query to improve retrieval accuracy. Defaults to
modelstringoptional- The model to use for query rewriting.
rewrite_promptstringoptional- A custom prompt to guide query rewriting.
rerankingobjectoptionalenabledbooleanoptional- Reorders retrieved results based on semantic relevance using a reranking model. Defaults to
false.
- Reorders retrieved results based on semantic relevance using a reranking model. Defaults to
modelstringoptional- The reranking model to use. Valid value:
@cf/baai/bge-reranker-base.
- The reranking model to use. Valid value:
match_thresholdnumberoptional- The minimum score for reranked results. Must be between
0and1. Defaults to0.4.
- The minimum score for reranked results. Must be between
cacheobjectoptionalenabledbooleanoptional- Override the instance-level cache setting for this request.
cache_thresholdstringoptional- The similarity threshold for cache hits. Valid values:
super_strict_match,close_enough,flexible_friend,anything_goes.
- The similarity threshold for cache hits. Valid values:
Response
The response contains the following fields:
| Field | Type | Description |
|---|---|---|
query_kind |
string | The query input type: text, image, or multimodal. |
search_query |
string | The query used for the search. Omitted for image-only queries. |
chunks |
array | An array of matching content chunks. |
chunks[].id |
string | The unique identifier for the chunk. |
chunks[].type |
string | The type of content, typically text. |
chunks[].score |
number | The overall match score between 0 and 1. |
chunks[].text |
string | The text content of the chunk. |
chunks[].item |
object | Information about the source item. |
chunks[].item.key |
string | The file path or URL of the source document. |
chunks[].item.timestamp |
number | Unix timestamp of when the item was last modified. |
chunks[].item.metadata |
object | Custom metadata associated with the source item. |
chunks[].scoring_details |
object | Breakdown of how the chunk was scored. |
chunks[].scoring_details.vector_score |
number | The semantic similarity score (0 to 1). |
chunks[].scoring_details.keyword_score |
number | The keyword (BM25) match score. Present when using hybrid or keyword retrieval. |
chunks[].scoring_details.keyword_rank |
number | The keyword rank position. |
chunks[].scoring_details.vector_rank |
number | The vector rank position. |
chunks[].scoring_details.reranking_score |
number | The reranking score (0 to 1). Present when reranking is enabled. |
chunks[].scoring_details.fusion_method |
string | The fusion method used (rrf or max). Present when using hybrid retrieval. |
chatCompletions()
Generate chat completions using your AI Search instance as context. This method retrieves relevant content and uses it to generate a response.
const instance = env.AI_SEARCH.get("my-instance");
const response = await instance.chatCompletions({
messages: [
{ role: "system", content: "You are a helpful documentation assistant." },
{ role: "user", content: "What is Cloudflare?" },
],
model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
ai_search_options: {
retrieval: {
max_num_results: 5,
},
query_rewrite: {
enabled: true,
},
},
});
Stream responses
Set stream: true to receive responses as Server-Sent Events (SSE) as they are generated:
const instance = env.AI_SEARCH.get("my-instance");
const stream = await instance.chatCompletions({
messages: [{ role: "user", content: "What is Cloudflare?" }],
stream: true,
});
return new Response(stream, {
headers: {
"content-type": "text/event-stream",
"cache-control": "no-cache",
},
});
When stream is enabled, the method returns a ReadableStream of SSE events. Each event contains a JSON object with choices[0].delta.content for incremental text. The stream ends with a data: [DONE] event.
Parameters
messages array required
An array of message objects representing the conversation. Each message has a role and content field.
rolestringrequired- The role of the message sender. Valid values:
system,developer,user,assistant,tool. contentstring | arrayrequired- The message content. Use a string for text, or an array containing
text,image_url, andfileparts. - A
textpart containstext. Animage_urlpart contains anhttps://URL or adata:image/<subtype>;base64,...URI. - A
filepart containsfile_dataas adata:<mime>;base64,...URI and afilename. The decoded file can be up to 10 MiB.
