Skip to main content

Overview

The webSearch tool performs web searches using SerpApi’s Google search engine integration. It returns a list of search results including titles, links, and snippets to provide a comprehensive overview of available information.

Function Signature

export const webSearch = ai.defineTool(
  {
    name: 'webSearch',
    description: 'Searches the web for a given query and returns a list of search results, including organic results, news, and academic papers to get a comprehensive overview.',
    inputSchema: WebSearchInputSchema,
    outputSchema: WebSearchOutputSchema,
  },
  async (input) => { ... }
);

Configuration

Environment Variables

SERPAPI_API_KEY
string
required
Your SerpApi API key. Obtain one from SerpApi.Error thrown if missing: SERPAPI_API_KEY is not configured. Please add it to your .env file.

Input Schema

The tool accepts input conforming to WebSearchInputSchema:
const WebSearchInputSchema = z.object({
  query: z.string().describe('The search query.'),
});

Parameters

query
string
required
The search query to execute. Can be any natural language search term.

Output Schema

Returns an array of search results conforming to WebSearchOutputSchema:
const WebSearchResultSchema = z.object({
  title: z.string().describe('The title of the search result.'),
  link: z.string().describe('The URL of the search result.'),
  snippet: z.string().describe('A brief summary of the search result.'),
});

const WebSearchOutputSchema = z.array(WebSearchResultSchema);

Response Fields

results
WebSearchResult[]
An array of search results, limited to the top 7 results.

Implementation Details

Search Parameters

The tool uses the following SerpApi parameters:
  • engine: google - Uses Google search engine
  • location: United States - Search results optimized for US location
  • api_key: From SERPAPI_API_KEY environment variable

Result Limiting

The tool returns a maximum of 7 results to keep the context focused for LLM processing. This helps maintain optimal performance and relevance.

Error Handling

errors
Error
The tool throws errors in the following cases:

Example Usage

import { webSearch } from '@/ai/tools/web-search';

// Perform a web search
const results = await webSearch({ query: 'climate change evidence' });

console.log(results);
// [
//   {
//     title: 'Climate Change Evidence: How Do We Know?',
//     link: 'https://climate.nasa.gov/evidence/',
//     snippet: 'This evidence is compelling: Ninety-seven percent of climate scientists agree that climate-warming trends over the past century...'
//   },
//   // ... up to 7 results
// ]

Source Code Location

src/ai/tools/web-search.ts:24-72

Build docs developers (and LLMs) love