Skip to main content
Instead of running the search yourself, let the model use Agentset as a search tool. The model decides what to search for, and follows up with additional queries as necessary. This handles multi-part questions, follow-ups, and ambiguous queries better than simple RAG, which retrieves only once before generating. It’s also the approach the playground chat uses to answer questions. This guide uses the Vercel AI SDK to wire an Agentset search tool into a tool-calling loop.

Prerequisites

  • An Agentset API key and namespace ID.
  • An OpenAI API key (or another AI SDK provider).
Install the dependencies:
Set your environment variables:
.env.local

System prompt

Use the system prompt below as a starting point and modify it for your use case:

Define the search tool

Wrap ns.search in an AI SDK tool. The model calls this tool with a query it generates, so describe the tool and its input clearly.

Run the agentic loop

Pass the tool to streamText. Set stopWhen so the model can run several searches before answering—without a limit, a tool-calling loop can run indefinitely.
The model runs the search tool as many times as it needs, then streams the final answer. Multi-part questions—like the billing example above—typically trigger separate searches for “failed payments” and “refunds.”

Multi-turn conversations

For a chat application, pass the full message history as messages instead of a single prompt. The model uses earlier turns to interpret follow-up questions and search accordingly.

Add citations

Return a stable identifier with each chunk and instruct the model to cite by it. Because the model reads chunks across several searches, citing by ID is more reliable than position-based numbering.
Add the citation contract to your system prompt:
See Citations for rendering citations in your UI.

Tune retrieval

Configure the underlying search per call to balance recall, relevance, and token usage. You can expose more than one tool—for example, one that fetches a full document by ID—and let the model choose between them.

Next steps

  • Search — Configure search parameters and reranking
  • Citations — Add source attribution to responses
  • Filtering — Scope searches with metadata filters
  • Observability — Trace each search and generation step