Workers binding (7)·续
model string optional
The text-generation model used to generate responses. Defaults to the generation model configured in the AI Search instance settings. For a list of supported models, refer to Supported models.
stream boolean optional
Returns a stream of results as they are generated. When enabled, returns a Response object with a readable stream. Defaults to false.
ai_search_options object optional
Configuration options for the search and generation 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 (non-streaming)
| Field | Type | Description |
|---|---|---|
id |
string | Unique identifier for the completion. |
object |
string | Always chat.completion. |
created |
number | Unix timestamp of when the completion was created. |
model |
string | The model used to generate the response. |
choices |
array | Array of completion choices. |
choices[].message.role |
string | Always assistant. |
choices[].message.content |
string | The generated response text. |
choices[].finish_reason |
string | Why the model stopped generating. Typically stop. |
usage.prompt_tokens |
number | Number of tokens in the prompt. |
usage.completion_tokens |
number | Number of tokens in the generated response. |
usage.total_tokens |
number | Total tokens used. |
chunks |
array | The source chunks used as context. Same format as the search response. |
Response (streaming)
When stream: true, the method returns a ReadableStream of Server-Sent Events. The retrieved chunks are sent first as a chunks event, followed by the streamed response.
event: chunks
data: [{"id":"chunk-001","type":"text","score":0.85,"text":"...","item":{"key":"about-cloudflare.md","timestamp":1775925540000},"scoring_details":{"vector_score":0.85}}]
data: {"id":"id-1776072781845","created":1776072781,"model":"@cf/meta/llama-3.3-70b-instruct-fp8-fast","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" document"}}]}
data: {"id":"id-1776072781845","created":1776072781,"model":"@cf/meta/llama-3.3-70b-instruct-fp8-fast","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" you provided doesn"}}]}
data: {"id":"id-1776072781845","created":1776072781,"model":"@cf/meta/llama-3.3-70b-instruct-fp8-fast","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"'t contain"}}]}
data: {"id":"id-1776072781845","created":1776072781,"model":"@cf/meta/llama-3.3-70b-instruct-fp8-fast","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" information"}}]}
data: [DONE]
Namespace methods
The following methods are only available when using the ai_search_namespaces binding. Search and chat across multiple instances in a single call using the namespace handle directly (env.AI_SEARCH).
search()
Pass instance_ids in ai_search_options to specify which instances to query. Results are merged and ranked, and each chunk includes an instance_id field identifying which instance it came from.
const results = await env.AI_SEARCH.search({
messages: [{ role: "user", content: "What is Cloudflare?" }],
ai_search_options: {
instance_ids: ["product-docs", "customer-abc123"],
},
});
Parameters
Same as instance-level search, with one additional required field:
| Parameter | Type | Required | Description |
|---|---|---|---|
ai_search_options |
object | Yes | Required for namespace-level search. |
ai_search_options.instance_ids |
array | Yes | Instance IDs to search across. Minimum 1, maximum 10. |
Response
Same as instance-level search, with additional fields:
| Field | Type | Description |
|---|---|---|
chunks[].instance_id |
string | The instance this chunk came from. |
errors |
array | Per-instance errors if any instances failed. Each object has instance_id and message. |
chatCompletions()
Generate chat completions using context retrieved from multiple instances.
const response = await env.AI_SEARCH.chatCompletions({
messages: [{ role: "user", content: "What is Cloudflare?" }],
ai_search_options: {
instance_ids: ["product-docs", "customer-abc123"],
},
});
Streaming is supported with stream: true.
Parameters
Same as instance-level chat completions, with one additional required field:
| Parameter | Type | Required | Description |
|---|---|---|---|
ai_search_options |
object | Yes | Required for namespace-level chat completions. |
ai_search_options.instance_ids |
array | Yes | Instance IDs to search across. Minimum 1, maximum 10. |
Response
Same as instance-level chat completions, with additional fields on each chunk:
| Field | Type | Description |
|---|---|---|
chunks[].instance_id |
string | The instance this chunk came from. |
errors |
array | Per-instance errors if any instances failed. Each object has instance_id and message. |
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,
},
],
}
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai-search/api/search/workers-binding/#page","headline":"Workers binding","description":"Search and chat with AI Search instances from a Cloudflare Worker using the Workers binding.","url":"https://developers.cloudflare.com/ai-search/api/search/workers-binding/","inLanguage":"en","image":"https://developers.cloudflare.com/ai-search/api/search/workers-binding/og.png?v=fa78d292a041eecc","dateModified":"2026-10-01","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
description: Send and query unlimited-cardinality analytics from Workers. title: Workers Analytics Engine image: https://developers.cloudflare.com/analytics/analytics-engine/og.png?v=dfb72c4220270535
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/analytics/llms.txt
Use this file to discover all available pages before exploring further.
Docs