AI Search Agent Integration, SDK Retrieval Tools, and Hybrid RAG
How to connect a managed search instance to Agents SDK, Vercel AI SDK, and LangChain for grounded retrieval, tool-calling agents, and citations.
This page summarizes Cloudflare documentation on using AI Search from popular agent and application frameworks. AI Search runs indexing, hybrid retrieval, and optional answer generation so agents can pull facts from product docs, support content, uploaded files, R2, or websites without building retrieval infrastructure yourself.
Agents can use AI Search to retrieve relevant information from indexed content and use it to augment calls to AI models. AI Search manages the retrieval pipeline for you, including indexing, search, and optional chat completions over your content.
— Cloudflare, AI Search
For creating and managing instances outside these guides, Cloudflare points to the Workers binding, REST API, or Wrangler commands. The Agents hub covers Agents SDK, AI SDK, and LangChain.
When to use AI Search from an agent
Section titled “When to use AI Search from an agent”Use AI Search when an agent should search a knowledge base, retrieve chunks before calling a model, or rely on managed indexing instead of custom vector pipelines.
| Goal | Typical approach |
|---|---|
| Answer in one call with sources | instance.chat() (AI SDK) or chatCompletions() (binding) |
| Let the model choose when to search | Expose instance.search() as a tool |
| Retrieval only; your own LLM | search() then pass chunks to another model |
| Python / LangChain stacks | CloudflareAISearchRetriever |
New instances use hybrid search by default (vector plus keyword indexes). Uploads are asynchronous: upload() queues work and returns immediately, so production code often polls item status or uses uploadAndPoll() before the first query.
Query patterns: generate, stream, or search-as-tool
Section titled “Query patterns: generate, stream, or search-as-tool”From the AI SDK guide, there are three ways to query an instance:
- Generate a response — full answer in one call.
- Stream a response — token streaming for chat UIs.
- Search as a tool — the model decides when to retrieve; recommended for agents.
With the Vercel AI SDK, instance.chat() plugs into generateText or streamText so retrieval and generation happen in one step, with chunks returned as sources:
Pass instance.chat() to generateText, and AI Search retrieves relevant content and generates a response in one call.
— Cloudflare, Generate a response
For agent loops, expose instance.search() instead of the chat model, because chat() retrieves on every request:
With chat(), AI Search searches your instance on every request. To let the model decide when to search instead, expose instance.search() as an AI SDK tool and pass it to a model that supports function calling, such as a Workers AI model. This is the pattern to use in an agent, where the model chooses between searching and other tools.
— Cloudflare, Search as a tool
Cap tool loops with stopWhen: stepCountIs(5) (or similar) so the model cannot invoke tools indefinitely.
Workers binding without the AI SDK provider
Section titled “Workers binding without the AI SDK provider”From AI Search as an agent tool, bind AI_SEARCH to the Worker and call search() or chatCompletions():
const instance = this.env.AI_SEARCH.get("my-instance");const results = await instance.search({ messages: [{ role: "user", content: query }],});For combined retrieval and generation on the binding:
const response = await instance.chatCompletions({ messages: [{ role: "user", content: "How do I deploy an Agent?" }], model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast", ai_search_options: { retrieval: { max_num_results: 5 } },});Vercel AI SDK: ai-search-provider
Section titled “Vercel AI SDK: ai-search-provider”The ai-search-provider package targets AI SDK v6 (ai@^6). Wrap the Workers namespace with createAISearchNamespace({ binding: env.AI_SEARCH }).
Install:
npm i ai ai-search-providerInstance creation stays on the binding (env.AI_SEARCH.create), not on the provider client. Creating a duplicate instance throws; idempotent setup uses try/catch.
Hybrid retrieval in generateText:
const { text, sources } = await generateText({ model: aiSearch.get(INSTANCE_NAME).chat({ ai_search_options: { retrieval: { retrieval_type: "hybrid", max_num_results: 5 }, }, }), messages: [{ role: "user", content: query }],});Version constraint: For search-as-tool with Workers AI, use workers-ai-provider@^3 with Zod — v4 expects AI SDK v7 and conflicts with ai-search-provider v6.
Cloudflare Agents SDK: stateful chat with tools
Section titled “Cloudflare Agents SDK: stateful chat with tools”The Agents SDK guide builds a stateful agent on Workers that provisions an AI Search instance, seeds a document, and exposes tools to the chat model.
The Cloudflare Agents SDK lets you build stateful AI agents that run on Workers. This guide builds a chat agent that provisions its own AI Search instance, indexes a document, and then searches that content with a tool before it answers.
— Cloudflare, Agents SDK
The recommended pattern wires search() as search_knowledge_base and optionally save_resolution to upload resolved answers. The orchestration model must support function calling — not the AI Search chat model — because the agent chooses when to search:
The agent exposes AI Search’s search() as a tool instead of using AI Search’s own chat model, so this model must support function calling to decide when to search and drive the tool calls.
— Cloudflare, Agents SDK — Write the agent
After ensureInstance(), hybrid search runs inside the tool’s execute via ai_search_options.retrieval. Route requests with routeAgentRequest from the agents package. Deeper agent-side API notes live under AI Search as an agent tool and Connect your AI Search to an MCP client (query from a Cloudflare Agent in code).
LangChain: CloudflareAISearchRetriever
Section titled “LangChain: CloudflareAISearchRetriever”The LangChain guide uses langchain-cloudflare for retrieval only; instance lifecycle uses the Cloudflare Python SDK.
The retriever only searches. To create an instance and upload content, pair it with the Cloudflare Python SDK.
— Cloudflare, LangChain
Three usage modes match the AI SDK split:
| Mode | Mechanism |
|---|---|
| Search directly | retriever.invoke("…") |
| Agent tool | create_retriever_tool(retriever, …) — described as the recommended agent path |
| RAG chain | Retriever + ChatCloudflareWorkersAI LCEL chain |
Set retrieval_type="hybrid" and k (mapped to max_num_results, capped at 50). In a Python Worker, pass a dedicated ai_search binding and use ainvoke — not the Workers AI binding self.env.AI.
Changelog coverage: Use AI Search with the Agents SDK, AI SDK, and LangChain and the AI Search release note.
Bring your own generation model
Section titled “Bring your own generation model”Default answers use Workers AI. To retrieve with AI Search and generate elsewhere, call search(), format chunks, then call your model — see Bring your own generation model.
By default, AI Search uses a Workers AI model to generate responses. To use a model outside of Workers AI, use AI Search for search and pass the retrieved content to a different model for generation.
— Cloudflare, Bring your own generation model
Cloudflare notes native third-party models via AI Gateway in AI Search settings; the manual search-then-generate pattern still applies when you fully control the prompt assembly.
The same split applies in agent design: search-as-tool + external LLM mirrors the OpenAI example in that guide.
Citations and source chunks
Section titled “Citations and source chunks”Show source citations in responses explains that chatCompletions() (and search()) return chunks with item.key, score, and text for UI citations. With the AI SDK, retrieved chunks appear as source parts in sources next to text. Group by item.key when multiple chunks reference one document.
Voice and long-running agents can log or speak answers while still surfacing chunk.item.key for audit — see Talk to your knowledge base, which uses search() inside a tool for grounded voice replies.
Namespace search across multiple instances
Section titled “Namespace search across multiple instances”When one agent must query shared plus tenant-specific indexes, use namespace-level env.AI_SEARCH.search() with ai_search_options.instance_ids (1–10 IDs). Each chunk includes instance_id; partial failures appear in errors instead of failing the whole request. Details: Search across multiple instances.
Common mistakes
Section titled “Common mistakes”- Calling
get("id")beforecreate({ id })and expecting a new instance. - Using
instance.chat()as the tool-calling model in an agent that should search selectively. - Querying immediately after
upload()without waiting for indexing (queued/runningstatuses). - Installing
workers-ai-provider@^4alongsideai-search-provider(AI SDK v6 vs v7 mismatch). - Assuming LangChain’s retriever creates instances — provision and upload separately.
- Searching the wrong binding in Python Workers (
MY_SEARCHai_search binding vsself.env.AI).
For broader use cases (simple search Worker, multitenancy, web fetch indexing), see the How to index. Managed RAG context appears in Cloudflare’s RAG reference diagram, which positions AI Search as a managed ingestion-and-query option.
How to check this on your site
Section titled “How to check this on your site”-
Create or select an AI Search instance and binding using the Workers binding get-started or dashboard flow, then run
npx wrangler devlocally. -
Hit your
/setup(or equivalent) route once and confirm the indexed item reaches a searchable status (notqueuedorrunning). -
Run a test query through your chosen path — binding
search(), AI SDKgenerateTextwithinstance.chat(), or a LangChainretriever.invoke— and verify non-empty chunks orsources. -
If using search-as-tool, send a question that requires corpus knowledge and confirm the model issues a tool call before answering; confirm
stepCountIsstops runaway loops. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.