How to Add Web Search to the Vercel AI SDK With the You.com API

How to Add Web Search to the Vercel AI SDK With the You.com API
TLDR: The Vercel AI SDK does not ship a built-in web search tool, so you add one yourself with its tool() helper, and the You.com Web Search API fits that slot with one client, one call, and typed JSON results the model can consume directly. This guide wires a search tool into generateText and streamText, covers the MCP-client route for teams that prefer a server, and names the failure modes that break agent apps in production.
What is the vercel ai sdk web search pattern? Define a tool with tool() from the ai package, give it a Zod input schema with the query, and execute the search by calling the You.com Web Search API's POST /v1/search endpoint with your key. The model calls the tool during generation, receives the structured results, and cites URLs from them.
The AI SDK is a provider-agnostic TypeScript toolkit for building AI applications and agents, published as the ai package on npm, developed in the open in the vercel/ai repository (Vercel AI SDK README, fetched September 2026). Its tool-calling core is what turns any HTTP API into a model-callable capability, and the You.com Web Search API is a natural fit because its results arrive as clean JSON with URLs, titles, descriptions, and snippets, which is exactly the shape a model can act on without parsing. For the same wiring in other frameworks, see our guides for LangChain and CrewAI.
How Do You Define a Web Search Tool?
A tool in the AI SDK has three core elements the model sees or triggers: a description that influences when the tool gets picked, an input schema that defines and validates the parameters, and an optional async execute function that produces the result (Vercel AI SDK tool calling documentation, fetched September 2026). Here is the full search tool against the You.com endpoint, with the error handling an agent actually needs.
import { z } from "zod"
import { generateText, tool } from "ai"
import { anthropic } from "@ai-sdk/anthropic" // or any provider
const YDC_KEY = process.env.YDC_API_KEY // from you.com/platform
const webSearch = tool({
description: "Search the live web. Returns results with url, title, and description.",
inputSchema: z.object({
query: z.string().describe("The search query"),
}),
execute: async ({ query }) => {
const res = await fetch("https://api.you.com/v1/search", {
method: "POST",
headers: {
"X-API-Key": YDC_KEY ?? "",
"Content-Type": "application/json",
},
body: JSON.stringify({ query, count: 5 }),
})
if (!res.ok) {
if (res.status === 401) throw new Error("YDC auth failed: check YDC_API_KEY")
if (res.status === 429) throw new Error("YDC rate limited: back off and retry")
throw new Error(`search failed: ${res.status}`)
}
const data = await res.json()
const web = data.results?.web ?? []
return {
results: web.map((r: any) => ({
url: r.url,
title: r.title,
description: r.description,
})),
}
},
})
const result = await generateText({
model: anthropic("claude-opus-4-6"),
tools: { webSearch },
prompt: "What shipped in the latest Postgres minor release? Cite URLs.",
})
console.log(result.text)
Three details in that tool are doing real work. The description tells the model what the tool is for, which is how it decides to search rather than answer from stale training data. The Zod schema both describes the input to the model and validates what it sends, so a malformed call fails fast instead of hitting the API. And the execute function returns trimmed results rather than the raw response, which keeps token consumption down, because the model reads only what it needs.
Why Trim the Results Before the Model Reads Them?
Every token the tool returns lands in the model's context, and search responses are token-heavy. The You.com API can return up to 100 results per call, each with description, snippets, and metadata (You.com search documentation, September 2026). A tool that returns all of them burns context on results the model will never cite.
The concrete failure mode to detect: context exhaustion masquerading as a quality problem. The symptom is an agent that searches successfully, then produces a short or degraded answer, and the cause is the tool result crowding out the model's working space. Detection is to log the token count of tool results alongside the final answer length. The fix is what the code above already does: cap count, trim fields, and return the minimum viable result set.
Decision framework: count 5 for single-answer agents, count 10 when the model must compare sources, and full extraction only when the task genuinely needs page text rather than snippets. The tradeoff is coverage against context, and the wrong side of it fails silently.
How Do You Stream With the Tool in a Chat App?
The same tool object plugs into streamText and the AI SDK UI hooks, which is the standard chatbot shape. Multi-step calls need a stop condition, and the AI SDK's current API uses stopWhen for that (Vercel AI SDK tool calling documentation, fetched September 2026).
import { streamText, tool, isStepCount } from "ai"
import { z } from "zod"
const result = streamText({
model: anthropic("claude-opus-4-6"),
tools: { webSearch },
stopWhen: isStepCount(5),
prompt: "Research this question and answer with citations.",
})
The step limit is not decoration. An agent with a search tool and no stop condition can loop, searching for a better answer forever, and every iteration costs both model tokens and search calls. Cap the steps at what your task actually needs, usually three to five.
When Should You Use the MCP Client Instead of a Custom Tool?
The AI SDK also supports connecting to Model Context Protocol servers through its MCP client in @ai-sdk/mcp, with HTTP transport recommended for production deployments (Vercel AI SDK MCP documentation, fetched September 2026). The You.com MCP server at https://api.you.com/mcp exposes the search capability as a ready-made tool, so instead of writing the execute function yourself, the client discovers the server's tools and adapts them.
import { createMCPClient } from "@ai-sdk/mcp"
const mcpClient = await createMCPClient({
transport: {
type: "http",
url: "https://api.you.com/mcp",
headers: { Authorization: `Bearer ${YDC_KEY}` },
},
})
const tools = await mcpClient.tools()
// pass `tools` to generateText or streamText
// await mcpClient.close() when done
The tradeoff, named: a custom tool gives you exact control over what the model sees, including the field trimming from earlier, and costs you the maintenance of the execute function. The MCP client gives you the server's tools with zero glue code, and costs you the server's tool definitions in your context and whatever result shape it returns. Schema discovery loads all the tools the server offers, which is more context than a search-only agent needs.
For the same server wired into coding agents rather than AI SDK apps, our Cursor web search guide covers the config-file route, and the MCP server comparison guide covers when one MCP install beats an embedded SDK.
What Does the You.com API Give the Tool to Work With?
The tool's quality ceiling is the API behind it. The You.com Web Search API returns unified results from web and news sources in a single request, every result carrying URL, title, description, snippets or query-relevant highlights, and metadata such as publication timestamps (You.com search documentation, September 2026). Optional parameters cover recency filtering (day, week, month, year, or a date range), country and language targeting, and domain include, exclude, and boost lists of up to 500 domains each. Search operators like site: and filetype: work inside the query string itself.
For agents that need page text, the same API attaches full page content per result in Markdown or HTML via the extraction object on the POST endpoint, which the JavaScript SDK guide covers in detail.
What Are the Failure Modes in Production?
Three break agent apps after they work in demo. First, unhandled 401 and 429 responses: the tool throws, the generation crashes, and the user sees a raw error. The code above converts both to explicit messages and the retry decision becomes yours. Second, empty results flowing downstream as success: an empty web array is a valid response, and a tool that returns it without marking it lets the model hallucinate sources. Third, unclosed MCP clients: the AI SDK docs recommend closing the client when generation ends, and a leaked connection pool in a serverless runtime surfaces as cold-start timeouts much later.
Detection for all three is logging at the tool boundary: status code, result count, and client lifecycle per call. Ten lines of logging at that boundary will catch more production incidents than any amount of prompt engineering.
Next action: install ai, @ai-sdk/anthropic, and zod, paste the tool from this guide, and run it against a question from your own domain with a key from the You.com platform. Then add the boundary logging before it ships. Usage rates are listed on the You.com pricing page.
Related Guides
LI Test
LI Test
Share Article:
Related resources.

Self-Hosted LLM Serving: Picking a Stack That Survives Real Traffic
September 16, 2026
Blog

What Is On-Premise AI? Deploying Intelligence Inside Your Own Infrastructure
September 15, 2026
Blog

How to Run an LLM Locally: A Practical Walkthrough for Developers
September 15, 2026
Blog

Google CSE Alternative in 2026: How to Replace the Custom Search JSON API
September 11, 2026
Blog

