import { generateText, tool, stepCountIs } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
import { tavily } from '@tavily/core';
export const tavilyClient = tavily(process.env.TAVILY_API_KEY);
export const AdvancedwebSearch = tool({
description: 'Search the web for up-to-date information',
inputSchema: z.object({
query: z.string().min(1).max(100).describe('The search query'),
maxResults: z.number().min(1).max(20).optional().describe('Maximum number of results to return'),
searchDepth: z.enum(['basic', 'advanced']).optional().describe('Search depth level'),
timeRange: z.enum(['week']).optional().describe('Time range for search results'),
}),
execute: async ({
query,
maxResults = 5,
searchDepth = 'advanced',
timeRange = 'week',
}) => {
const response = await tavilyClient.search(query, {
max_results: maxResults,
search_depth: searchDepth,
time_range: timeRange,
});
return response.results.map(result => ({
title: result.title,
url: result.url,
content: result.content,
score: result.score,
}));
},
});
const { text } = await generateText({
model: openai('gpt-4o-mini'), // can be any model that supports tools
prompt: 'What happened in New York City last week?',
tools: {
AdvancedwebSearch,
},
stopWhen: stepCountIs(5),
});
console.log(text);