Files
povtornyy-ekzamen-2-sravnit…/src/utils.js
T

46 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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<Object>} - 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) {
// Rethrow with a more descriptive message
throw new Error(`Failed to fetch from Tavily: ${err.message}`);
}
}