/** * Utility functions for interacting with the Tavily API. * * This module contains a single approach: async/await based HTTP requests * using the native fetch API (via node-fetch). All functions return Promises * and throw descriptive errors on failure. */ import fetch from 'node-fetch'; /** * Performs a search query against the Tavily API. * * @param {string} query - The search query string. * @returns {Promise} - The JSON response from Tavily. * @throws {Error} - If the request fails or the API returns an error. */ export async function tavilySearch(query) { const apiKey = process.env.TAVILY_API_KEY; if (!apiKey) { throw new Error('TAVILY_API_KEY environment variable is not set.'); } const url = `https://api.tavily.com/search?query=${encodeURIComponent(query)}`; try { const response = await fetch(url, { method: 'GET', headers: { 'Authorization': `Bearer ${apiKey}`, 'Accept': 'application/json' } }); if (!response.ok) { const errorText = await response.text(); throw new Error(`Tavily API error: ${response.status} ${response.statusText} - ${errorText}`); } const data = await response.json(); return data; } catch (err) { // Re‑throw with a more descriptive message throw new Error(`Failed to fetch from Tavily: ${err.message}`); } }