feat: solution for 'Повторный экзамен #2: Сравнительный обзор 3 сущностей (Tavily)'

This commit is contained in:
2026-07-01 13:23:40 +03:00
parent f1bd10bd09
commit c11f8de6a7
8 changed files with 299 additions and 164 deletions
+46
View File
@@ -0,0 +1,46 @@
/**
* 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}`);
}
}