### Generation System Prompt Example Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/system-prompt This example demonstrates a system prompt designed to guide an AI model in generating responses based on retrieved documents. It specifies the model's role, the expected inputs, and the desired output format and constraints. ```text You are a helpful AI assistant specialized in answering questions using retrieved documents. Your task is to provide accurate, relevant answers based on the matched content provided. For each query, you will receive: User's question/query A set of matched documents, each containing: - File name - File content You should: 1. Analyze the relevance of matched documents 2. Synthesize information from multiple sources when applicable 3. Acknowledge if the available documents don't fully answer the query 4. Format the response in a way that maximizes readability, in Markdown format Answer only with direct reply to the user question, be concise, omit everything which is not directly relevant, focus on answering the question directly and do not redirect the user to read the content. If the available documents don't contain enough information to fully answer the query, explicitly state this and provide an answer based on what is available. Important: - Cite which document(s) you're drawing information from - Present information in order of relevance - If documents contradict each other, note this and explain your reasoning for the chosen answer - Do not repeat the instructions ``` -------------------------------- ### Run React Development Server Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/embed-search-snippets Start your React development server after installing the package and adding the component. This command is typically used to test your application locally. ```bash npm run dev ``` -------------------------------- ### Install Wrangler using bun Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Install the Wrangler CLI using bun. This is a fast, all-in-one JavaScript runtime for installing Wrangler. ```bash bun install wrangler ``` -------------------------------- ### Install Wrangler using npm Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Install the Wrangler CLI using npm. This is the first step to using Wrangler commands. ```bash npm install wrangler ``` -------------------------------- ### Create a new AI Search instance Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Create a new AI Search instance with a specified name. This is the fundamental command to get started. ```bash wrangler ai-search create my-instance ``` -------------------------------- ### Example Tool Description for MCP Clients Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/public-endpoint/index.md Provides an example of a tool description for MCP clients, explaining the content indexed and the types of questions the AI Search tool can answer. ```text Search the Acme product documentation for information about installation, configuration, API references, and troubleshooting guides. Use this tool when users ask questions about how to set up or use Acme products. ``` -------------------------------- ### Example Tool Description for MCP Clients Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/public-endpoint An example of a tool description used to inform AI agents about the capabilities of your AI Search instance. This description helps agents determine when to use the search tool. ```text Search the Acme product documentation for information about installation, configuration, API references, and troubleshooting guides. Use this tool when users ask questions about how to set up or use Acme products. ``` -------------------------------- ### Query Rewriting System Prompt Example Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/system-prompt This example shows a system prompt for query rewriting. It instructs the model to optimize user queries for semantic retrieval by identifying core concepts, adding synonyms, and removing filler words. ```text You are a search query optimizer for vector database searches. Your task is to reformulate user queries into more effective search terms. Given a user's search query, you must: 1. Identify the core concepts and intent 2. Add relevant synonyms and related terms 3. Remove irrelevant filler words 4. Structure the query to emphasize key terms 5. Include technical or domain-specific terminology if applicable Provide only the optimized search query without any explanations, greetings, or additional commentary. Example input: "how to fix a bike tire that's gone flat" Example output: "bicycle tire repair puncture fix patch inflate maintenance flat tire inner tube replacement" Constraints: - Output only the enhanced search terms - Keep focus on searchable concepts - Include both specific and general related terms - Maintain all important meaning from original query ``` -------------------------------- ### Install Wrangler using pnpm Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Install the Wrangler CLI using pnpm. This is another alternative package manager for installing Wrangler. ```bash pnpm install wrangler ``` -------------------------------- ### Create an AI Search instance connected to a website Source: https://developers.cloudflare.com/ai-search/get-started/api Create an instance that automatically crawls and indexes content from a specified website. Replace `` with your account ID. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ "id": "my-instance", "type": "web-crawler", "source": "example.com" }' ``` -------------------------------- ### Search AI Search Instance Source: https://developers.cloudflare.com/ai-search/llms-full.txt This TypeScript example shows how to get a specific AI Search instance and perform a search query. The results include scored chunks and source references. ```typescript const instance = env.AI_SEARCH.get("my-instance"); const results = await instance.search({ messages: [{ role: "user", content: "What is Cloudflare?" }], }); ``` -------------------------------- ### Install Wrangler using yarn Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Install the Wrangler CLI using yarn. This is an alternative package manager for installing Wrangler. ```bash yarn install wrangler ``` -------------------------------- ### Create a basic AI Search instance Source: https://developers.cloudflare.com/ai-search/get-started/api Use this endpoint to create a new AI Search instance. Replace `` with your account ID and ensure you have a valid API token. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ "id": "my-instance" }' ``` -------------------------------- ### Create AI Search Instance with Content Selectors Source: https://developers.cloudflare.com/ai-search/configuration/data-source/website/index.md Configure content selectors when creating a new AI Search instance via the API. This example shows how to specify selectors for blog and documentation paths. ```bash curl "https://api.cloudflare.com/client/v4/accounts/{account_id}/ai-search/instances" \ -H "Authorization: Bearer {api_token}" \ -H "Content-Type: application/json" \ -d '{ \ "id": "my-ai-search", \ "source": "https://example.com", \ "type": "web-crawler", \ "source_params": { \ "web_crawler": { \ "parse_options": { \ "content_selector": [ \ { \ "path": "**/blog/**", \ "selector": "article .post-body" \ }, \ { \ "path": "**/docs/**", \ "selector": "main .content" \ } \ ] \ } \ } \ } \ }' ``` -------------------------------- ### Create an AI Search instance for a website Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Create an AI Search instance configured to crawl and index a website. Specify the type as 'web-crawler' and provide the source URL. ```bash wrangler ai-search create my-instance --type web-crawler --source developers.cloudflare.com ``` -------------------------------- ### Streaming Response Example Source: https://developers.cloudflare.com/ai-search/api/search/rest-api Example of Server-Sent Events (SSE) for streaming responses. It shows chunks of data followed by the final response. ```text 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] ``` -------------------------------- ### AI Search Instance Response Example Source: https://developers.cloudflare.com/ai-search/llms-full.txt This is an example JSON response when listing AI Search instances. It details various configuration options for an instance. ```json { "result": [ { "id": "my-ai-search", "created_at": "2019-12-27T18:11:19.117Z", "modified_at": "2019-12-27T18:11:19.117Z", "ai_gateway_id": "ai_gateway_id", "ai_search_model": "@cf/meta/llama-3.3-70b-instruct-fp8-fast", "cache": true, "cache_threshold": "super_strict_match", "cache_ttl": 600, "chunk_overlap": 0, "chunk_size": 64, "created_by": "created_by", "custom_metadata": [ { "data_type": "text", "field_name": "x" } ], "embedding_model": "@cf/qwen/qwen3-embedding-0.6b", "enable": true, "engine_version": 0, "fusion_method": "max", "hybrid_search_enabled": true, "index_method": { "keyword": true, "vector": true }, "indexing_options": { "keyword_tokenizer": "porter" }, "last_activity": "2019-12-27T18:11:19.117Z", "max_num_results": 1, "metadata": { "created_from_aisearch_wizard": true, "worker_domain": "worker_domain" }, "modified_by": "modified_by", "namespace": "namespace", "paused": true, "public_endpoint_id": "public_endpoint_id", "public_endpoint_params": { "authorized_hosts": [ "string" ], "chat_completions_endpoint": { "disabled": true }, "enabled": true, "mcp": { "description": "description", "disabled": true }, "rate_limit": { "period_ms": 60000, "requests": 1, "technique": "fixed" }, "search_endpoint": { "disabled": true } }, "reranking": true, "reranking_model": "@cf/baai/bge-reranker-base", "retrieval_options": { "boost_by": [ { "field": "timestamp", "direction": "desc" } ], "keyword_match_mode": "and" }, "rewrite_model": "@cf/meta/llama-3.3-70b-instruct-fp8-fast", "rewrite_query": true, "score_threshold": 0, "source": "source", "source_params": { "exclude_items": [ "/admin/**", "/private/**", "**\\temp\\**" ], "include_items": [ "/blog/**", "/docs/**/*.html", "**\\blog\\**.html" ], "prefix": "prefix", "r2_jurisdiction": "r2_jurisdiction", "web_crawler": { "crawl_options": { "depth": 1, "include_external_links": true, "include_subdomains": true, "max_age": 0, "source": "all" }, "parse_options": { "content_selector": [ { "path": "**/blog/**", "selector": "article div.post-body" }, { "path": "**/docs/**", "selector": "main" } ], "include_headers": { "cache-control": "no-cache, no-store" }, "include_images": true, "specific_sitemaps": [ "https://example.com/sitemap.xml", "https://example.com/blog-sitemap.xml" ], "use_browser_rendering": true }, "parse_type": "sitemap", "store_options": { "storage_id": "storage_id", "r2_jurisdiction": "r2_jurisdiction", "storage_type": "r2" } } }, "status": "status", "sync_interval": 900, "token_id": "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", "type": "r2" } ], "result_info": { "count": 0, "page": 0, "per_page": 0, "total_count": 0 }, "success": true } ``` -------------------------------- ### AI Search Response Example Source: https://developers.cloudflare.com/ai-search/llms-full.txt This is an example of a response from an AI Search query, showing search results with file IDs, filenames, scores, and content snippets. ```json { "object": "vector_store.search_results.page", "search_query": "How do I train a llama to deliver coffee?", "data": [ { "file_id": "llama001", "filename": "llama/logistics/llama-logistics.md", "score": 0.45, "attributes": { "modified_date": 1735689600000, "folder": "llama/logistics/" }, "content": [ { "id": "llama001", "type": "text", "text": "Llamas can carry 3 drinks max." } ] }, { "file_id": "llama042", "filename": "llama/llama-commands.md", "score": 0.4, "attributes": { "modified_date": 1735689600000, "folder": "llama/" }, "content": [ { "id": "llama042", "type": "text", "text": "Start with basic commands like 'Espresso Express!' Llamas love alliteration." } ] } ], "has_more": false, "next_page": null } ``` -------------------------------- ### Example Chat Completions API Response Source: https://developers.cloudflare.com/ai-search/llms-full.txt This is an example of a successful response from the chat completions API. It includes 'choices' with message content and 'chunks' containing search result details. ```json { "choices": [ { "message": { "content": "content", "role": "system" }, "index": 0 } ], "chunks": [ { "id": "id", "score": 0, "text": "text", "type": "type", "item": { "key": "key", "metadata": { "foo": "bar" }, "timestamp": 0 }, "scoring_details": { "fusion_method": "rrf", "keyword_rank": 0, "keyword_score": 0, "reranking_score": 0, "vector_rank": 0, "vector_score": 0 } } ], "id": "id", "model": "model", "object": "object" } ``` -------------------------------- ### Full HTML Example with Search Bar Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/embed-search-snippets/index.md A complete HTML page demonstrating a search bar component that displays results in a dropdown. It includes the necessary script tag and the search bar element with additional `max-results` configuration. ```html ``` -------------------------------- ### Create an AI Search instance connected to a website Source: https://developers.cloudflare.com/ai-search/get-started/api/index.md Create an AI Search instance that automatically crawls and indexes content from a specified website. Ensure you replace placeholders with your actual account ID, API token, and website URL. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ \ "id": "my-instance", \ "type": "web-crawler", \ "source": "example.com" \ }' ``` -------------------------------- ### Run a query against an AI Search instance Source: https://developers.cloudflare.com/ai-search/get-started/api/index.md Execute a search query against your AI Search instance once content indexing is complete. This example demonstrates a basic user query. ```bash curl "https://api.cloudflare.com/client/v4/accounts//ai-search/instances/my-instance/search" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ \ "messages": [ \ { \ "content": "How do I get started?", \ "role": "user" \ } \ ] \ }' ``` -------------------------------- ### Website Data Source Path Filtering Examples Source: https://developers.cloudflare.com/ai-search/configuration/indexing/path-filtering/index.md Examples of include and exclude patterns for website data sources to index specific pages or exclude admin and login pages. ```text Include: **/blog/** Exclude: **/admin/** Exclude: **/login* Include: **/docs/**, Exclude: **/docs/drafts/** ``` -------------------------------- ### Create a basic AI Search instance Source: https://developers.cloudflare.com/ai-search/get-started/api/index.md Use this cURL command to create a new AI Search instance without a pre-defined data source. Replace `` and `` with your specific values. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ \ "id": "my-instance" \ }' ``` -------------------------------- ### Namespace Binding Methods - get() Source: https://developers.cloudflare.com/ai-search/api/instances/workers-binding Retrieve a handle to a specific AI Search instance within a namespace using the `get()` method. This operation is synchronous and resolves the instance lazily. ```APIDOC ## Namespace Binding Methods - `get()` ### Description Returns a handle to a specific instance within the namespace. This method is **synchronous** and does not make a network call. The instance is resolved lazily when you call methods like `search()` or `info()`. ### Method `env.AI_SEARCH.get(name: string)` ### Parameters | Parameter | Type | Required | Description | |---|---|---|---| | `name` | string | Yes | The name of the instance to get a handle to. | ### Example Usage ```javascript const instance = env.AI_SEARCH.get("my-instance"); const results = await instance.search({ messages: [{ role: "user", content: "What is Cloudflare?" }], }); ``` ``` -------------------------------- ### Create AI Search Instance with Boosting Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/boosting Configure relevance boosting when creating a new AI Search instance. This example promotes recent documents and higher priority items. ```javascript const instance = await env.AI_SEARCH.create({ id: "my-instance", retrieval_options: { boost_by: [ { field: "timestamp", direction: "desc" }, { field: "priority", direction: "desc" }, ], }, }); ``` -------------------------------- ### R2 Data Source Path Filtering Examples Source: https://developers.cloudflare.com/ai-search/configuration/indexing/path-filtering/index.md Examples of include and exclude patterns for R2 data sources to index specific file types or exclude temporary files and folders. ```text Include: /docs/**/*.pdf Exclude: **/*.tmp, **/*.bak Exclude: /temp/**, /backup/** Include: /docs/**, Exclude: /docs/drafts/** ``` -------------------------------- ### Install AI Search Snippet Package (npm) Source: https://developers.cloudflare.com/ai-search/configuration/retrieval/embed-search-snippets Install the AI Search snippet package in your React or Vue project using npm. This command is used before importing the package into your component files. ```bash npm install @cloudflare/ai-search-snippet ``` -------------------------------- ### Create R2-Backed AI Search Instance with Token Source: https://developers.cloudflare.com/ai-search/configuration/indexing/service-api-token Create an AI Search instance that uses an R2 bucket as a data source, providing the registered service API token ID. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ \ "id": "my-r2-docs", \ "type": "r2", \ "source": "", \ "token_id": "" \ }' ``` -------------------------------- ### Create an AI Search instance connected to an R2 bucket Source: https://developers.cloudflare.com/ai-search/get-started/api/index.md Create an AI Search instance to index documents from an R2 bucket. This requires an R2 bucket name and a service API token ID. If this is your first R2-backed instance, you must include the `token_id` field. ```bash curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ --data '{ \ "id": "my-instance", \ "type": "r2", \ "source": "", \ "token_id": "" \ }' ``` -------------------------------- ### AI Search API Response Example Source: https://developers.cloudflare.com/ai-search/api/migration/workers-binding-legacy This is an example of the JSON response received after performing an AI search query. It includes the search query, results data with file information and content, and pagination details. ```json { "object": "vector_store.search_results.page", "search_query": "How do I train a llama to deliver coffee?", "data": [ { "file_id": "llama001", "filename": "llama/logistics/llama-logistics.md", "score": 0.45, "attributes": { "modified_date": 1735689600000, "folder": "llama/logistics/" }, "content": [ { "id": "llama001", "type": "text", "text": "Llamas can carry 3 drinks max." } ] }, { "file_id": "llama042", "filename": "llama/llama-commands.md", "score": 0.4, "attributes": { "modified_date": 1735689600000, "folder": "llama/" }, "content": [ { "id": "llama042", "type": "text", "text": "Start with basic commands like 'Espresso Express!' Llamas love alliteration." } ] } ], "has_more": false, "next_page": null } ``` -------------------------------- ### Create an AI Search instance for an R2 bucket Source: https://developers.cloudflare.com/ai-search/get-started/wrangler Create an AI Search instance to index documents from an R2 bucket. Specify the type as 'r2' and provide the bucket name. ```bash wrangler ai-search create my-instance --type r2 --source my-bucket ``` -------------------------------- ### "Starts With" Folder Filter Source: https://developers.cloudflare.com/ai-search/api/migration/autorag-filter-format/index.md Use a compound filter with range operators ('gt' and 'lte') to match all files within a folder and its subfolders. This method effectively filters for paths that start with a specific prefix. ```javascript filters: { type: "and", filters: [ { type: "gt", key: "folder", value: "customer-a//" }, { type: "lte", key: "folder", value: "customer-a/z" } ] } ``` -------------------------------- ### Create an AI Search instance Source: https://developers.cloudflare.com/ai-search/get-started/api/index.md Use the Create instance API to create an AI Search instance. Replace `` with your account ID. ```APIDOC ## POST /accounts//ai-search/instances ### Description Creates a new AI Search instance. ### Method POST ### Endpoint /accounts//ai-search/instances ### Parameters #### Request Body - **id** (string) - Required - The ID for the new instance. - **type** (string) - Optional - The type of data source (e.g., "web-crawler", "r2"). - **source** (string) - Optional - The source of the data (e.g., a website URL or R2 bucket name). - **token_id** (string) - Optional - The service API token ID for R2 bucket connections. ### Request Example ```json { "id": "my-instance" } ``` ### Request Example with Website Source ```json { "id": "my-instance", "type": "web-crawler", "source": "example.com" } ``` ### Request Example with R2 Source ```json { "id": "my-instance", "type": "r2", "source": "", "token_id": "" } ``` ``` -------------------------------- ### Search using Namespace Binding Source: https://developers.cloudflare.com/ai-search/api/search/workers-binding Example of how to perform a search query using an AI Search namespace binding. It demonstrates retrieving an instance and calling the `search` method with user messages. ```javascript const instance = env.AI_SEARCH.get("my-instance"); const results = await instance.search({ messages: [{ role: "user", content: "What is Cloudflare?" }], }); ``` -------------------------------- ### Get Job Details Source: https://developers.cloudflare.com/ai-search/api/instances/rest-api/index.md Retrieves detailed information about a specific sync job. ```APIDOC ## GET /accounts//ai-search/instances//jobs/ ### Description Get detailed information about a specific sync job. ### Method GET ### Endpoint `/accounts//ai-search/instances//jobs/` ### Parameters #### Path Parameters - **ACCOUNT_ID** (string) - Required - Your Cloudflare account ID. - **INSTANCE_NAME** (string) - Required - The name of your AI Search instance. - **JOB_ID** (string) - Required - The unique identifier of the job. ### Response #### Success Response (200) - **@context** (string) - The JSON-LD context. - **@type** (string) - The type of the resource, typically 'Job'. - **id** (string) - The unique identifier for the job. - **status** (string) - The current status of the job. - **created_at** (string) - The timestamp when the job was created. - **updated_at** (string) - The timestamp when the job was last updated. - **data_source** (object) - Information about the data source being indexed. - **type** (string) - The type of the data source (e.g., 'website', 'sitemap'). - **url** (string) - The URL of the data source. - **index_config** (object) - Configuration details for the index. - **name** (string) - The name of the index. #### Response Example ```json { "@context": "https://schema.org", "@type": "Job", "id": "", "status": "completed", "created_at": "2023-10-26T15:00:00Z", "updated_at": "2023-10-26T15:10:00Z", "data_source": { "type": "website", "url": "https://example.com" }, "index_config": { "name": "my-index" } } ``` ``` -------------------------------- ### Breadcrumb List Schema Source: https://developers.cloudflare.com/ai-search/configuration/data-source/r2/index.md Example of a BreadcrumbList schema for AI Search R2 configuration. ```json {"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/ai-search/","name":"AI Search"}},{"@type":"ListItem","position":3,"item":{"@id":"/ai-search/configuration/","name":"Configuration"}},{"@type":"ListItem","position":4,"item":{"@id":"/ai-search/configuration/data-source/","name":"Data source"}},{"@type":"ListItem","position":5,"item":{"@id":"/ai-search/configuration/data-source/r2/","name":"R2"}}]} ``` -------------------------------- ### Create an Instance Source: https://developers.cloudflare.com/ai-search/api/instances/rest-api Use this cURL command to create a new AI Search instance in the default namespace. Ensure you replace and with your specific values. ```curl curl -X POST "https://api.cloudflare.com/client/v4/accounts//ai-search/instances" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "id": "my-instance" }' ``` -------------------------------- ### Get AI Search Instance Source: https://developers.cloudflare.com/ai-search/llms-full.txt Retrieves the details of a specific AI Search instance by its ID. ```APIDOC ## GET /accounts/{account_id}/ai-search/instances/{id} ### Description Retrieves the details of a specific AI Search instance. ### Method GET ### Endpoint /accounts/{account_id}/ai-search/instances/{id} ### Parameters #### Path Parameters - **account_id** (string) - Required - The ID of the account. - **id** (string) - Required - The ID of the AI Search instance. ### Response #### Success Response (200) - **result** (object) - Contains the details of the AI Search instance. - **id** (string) - The unique identifier for the AI Search instance. - **created_at** (string) - The timestamp when the instance was created. - **modified_at** (string) - The timestamp when the instance was last modified. - **ai_gateway_id** (string) - The ID of the associated AI Gateway. - **ai_search_model** (string) - The AI model used for search. - **cache** (boolean) - Whether caching is enabled. - **cache_threshold** (string) - The cache matching threshold. - **cache_ttl** (integer) - The cache time-to-live in seconds. - **chunk_overlap** (integer) - The overlap between text chunks. - **chunk_size** (integer) - The size of text chunks. - **created_by** (string) - The user or system that created the instance. - **custom_metadata** (array) - A list of custom metadata fields. - **embedding_model** (string) - The embedding model used. - **enable** (boolean) - Whether the instance is enabled. - **engine_version** (integer) - The version of the search engine. - **fusion_method** (string) - The method used for combining search results. - **hybrid_search_enabled** (boolean) - Whether hybrid search is enabled. - **index_method** (object) - Configuration for indexing methods. - **indexing_options** (object) - Options for indexing. - **last_activity** (string) - The timestamp of the last activity. - **max_num_results** (integer) - The maximum number of results to return. - **metadata** (object) - Additional metadata about the instance. - **modified_by** (string) - The user or system that last modified the instance. - **namespace** (string) - The namespace for the instance. - **paused** (boolean) - Whether the instance is paused. - **public_endpoint_id** (string) - The ID of the public endpoint. - **public_endpoint_params** (object) - Parameters for the public endpoint. - **reranking** (boolean) - Whether reranking is enabled. - **reranking_model** (string) - The reranking model used. - **retrieval_options** (object) - Options for retrieval. - **rewrite_model** (string) - The model used for query rewriting. - **rewrite_query** (boolean) - Whether query rewriting is enabled. - **score_threshold** (number) - The minimum score threshold for results. - **source** (string) - The data source for the instance. - **source_params** (object) - Parameters for the data source. - **status** (string) - The current status of the instance. - **sync_interval** (integer) - The synchronization interval in seconds. - **token_id** (string) - The ID of the token. - **type** (string) - The type of the instance. - **success** (boolean) - Indicates if the request was successful. #### Response Example ```json { "result": { "id": "my-ai-search", "created_at": "2019-12-27T18:11:19.117Z", "modified_at": "2019-12-27T18:11:19.117Z", "ai_gateway_id": "ai_gateway_id", "ai_search_model": "@cf/meta/llama-3.3-70b-instruct-fp8-fast", "cache": true, "cache_threshold": "super_strict_match", "cache_ttl": 600, "chunk_overlap": 0, "chunk_size": 64, "created_by": "created_by", "custom_metadata": [ { "data_type": "text", "field_name": "x" } ], "embedding_model": "@cf/qwen/qwen3-embedding-0.6b", "enable": true, "engine_version": 0, "fusion_method": "max", "hybrid_search_enabled": true, "index_method": { "keyword": true, "vector": true }, "indexing_options": { "keyword_tokenizer": "porter" }, "last_activity": "2019-12-27T18:11:19.117Z", "max_num_results": 1, "metadata": { "created_from_aisearch_wizard": true, "worker_domain": "worker_domain" }, "modified_by": "modified_by", "namespace": "namespace", "paused": true, "public_endpoint_id": "public_endpoint_id", "public_endpoint_params": { "authorized_hosts": [ "string" ], "chat_completions_endpoint": { "disabled": true }, "enabled": true, "mcp": { "description": "description", "disabled": true }, "rate_limit": { "period_ms": 60000, "requests": 1, "technique": "fixed" }, "search_endpoint": { "disabled": true } }, "reranking": true, "reranking_model": "@cf/baai/bge-reranker-base", "retrieval_options": { "boost_by": [ { "field": "timestamp", "direction": "desc" } ], "keyword_match_mode": "and" }, "rewrite_model": "@cf/meta/llama-3.3-70b-instruct-fp8-fast", "rewrite_query": true, "score_threshold": 0, "source": "source", "source_params": { "exclude_items": [ "/admin/**", "/private/**", "**\\temp\\**" ], "include_items": [ "/blog/**", "/docs/**/*.html", "**\\blog\\**.html" ], "prefix": "prefix", "r2_jurisdiction": "r2_jurisdiction", "web_crawler": { "crawl_options": { "depth": 1, "include_external_links": true, "include_subdomains": true, "max_age": 0, "source": "all" }, "parse_options": { "content_selector": [ { "path": "**/blog/**", "selector": "article div.post-body" }, { "path": "**/docs/**", "selector": "main" } ], "include_headers": { "cache-control": "no-cache, no-store" }, "include_images": true, "specific_sitemaps": [ "https://example.com/sitemap.xml", "https://example.com/blog-sitemap.xml" ], "use_browser_rendering": true }, "parse_type": "sitemap", "store_options": { "storage_id": "storage_id", "r2_jurisdiction": "r2_jurisdiction", "storage_type": "r2" } } }, "status": "status", "sync_interval": 900, "token_id": "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e", "type": "r2" }, "success": true } ``` ``` -------------------------------- ### Manage Per-Tenant AI Search Instances (JavaScript) Source: https://developers.cloudflare.com/ai-search/how-to/per-tenant-search/index.md Handles tenant onboarding, document uploads, searches, and offboarding using the AI Search namespace binding. It identifies tenants via the 'x-tenant-id' header and creates/manages isolated instances. ```javascript export default { async fetch(request, env) { const url = new URL(request.url); // Identify the tenant from the request header const tenantId = request.headers.get("x-tenant-id"); if (!tenantId) { return new Response("Missing x-tenant-id header", { status: 400 }); } // Create a new instance for the tenant if (url.pathname === "/onboard" && request.method === "POST") { const instance = await env.TENANTS.create({ id: `tenant-${tenantId}`, }); return Response.json({ success: true, instance: await instance.info() }); } // Upload a document to the tenant's instance if (url.pathname === "/upload" && request.method === "POST") { const formData = await request.formData(); const file = formData.get("file"); // Upload the file to the tenant's built-in storage const item = await env.TENANTS.get(`tenant-${tenantId}`).items.upload( file.name, await file.arrayBuffer(), ); return Response.json({ success: true, item }); } // Search the tenant's instance if (url.pathname === "/search") { const query = url.searchParams.get("q") || ""; // Each tenant's search is isolated to their own instance const results = await env.TENANTS.get(`tenant-${tenantId}`).search({ messages: [{ role: "user", content: query }], }); return Response.json(results); } // Delete the tenant's instance and all its data if (url.pathname === "/offboard" && request.method === "DELETE") { await env.TENANTS.delete(`tenant-${tenantId}`); return Response.json({ success: true }); } return new Response("Not found", { status: 404 }); }, }; ```