feat: solution for 'Повторный экзамен #2: Сравнительный обзор 3 сущностей (Tavily)'
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
import fetch from 'node-fetch';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export async function compareEntities(names) {
|
||||
const apiKey = process.env.TAVILY_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error('TAVILY_API_KEY environment variable is not set.');
|
||||
}
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const name of names) {
|
||||
try {
|
||||
const response = await fetch('https://api.tavily.com/search', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${apiKey}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: name,
|
||||
search_depth: 'basic',
|
||||
max_results: 1
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch data for "${name}". Status: ${response.status} ${response.statusText}`);
|
||||
results.push({ name, summary: 'Error fetching data' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const content = data.results && data.results[0] && data.results[0].content
|
||||
? data.results[0].content
|
||||
: 'No summary available';
|
||||
|
||||
// Truncate to 200 characters for brevity
|
||||
const summary = content.length > 200 ? content.slice(0, 200) + '...' : content;
|
||||
|
||||
results.push({ name, summary });
|
||||
} catch (err) {
|
||||
console.error(`Error processing "${name}": ${err.message}`);
|
||||
results.push({ name, summary: 'Error processing entity' });
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
+39
-87
@@ -1,99 +1,51 @@
|
||||
import fetch from 'node-fetch';
|
||||
import { compareEntities } from './compare.js';
|
||||
import { generateMarkdownTable } from './markdown.js';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const API_KEY = process.env.TAVILY_API_KEY;
|
||||
if (!API_KEY) {
|
||||
console.error('Error: TAVILY_API_KEY environment variable is not set.');
|
||||
process.exit(1);
|
||||
}
|
||||
function parseArgs() {
|
||||
const args = process.argv.slice(2);
|
||||
const entities = [];
|
||||
let outputFile = null;
|
||||
|
||||
const API_URL = 'https://api.tavily.com/search';
|
||||
|
||||
const ENTITIES = [
|
||||
'Apple Inc.',
|
||||
'Microsoft Corporation',
|
||||
'Google LLC'
|
||||
];
|
||||
|
||||
const ATTRIBUTES = ['Title', 'URL', 'Snippet', 'Score'];
|
||||
|
||||
async function fetchEntityData(entity) {
|
||||
try {
|
||||
const response = await fetch(API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: entity,
|
||||
search_depth: 'basic',
|
||||
include_raw_content: false,
|
||||
top_k: 1
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch data for "${entity}". Status: ${response.status}`);
|
||||
return null;
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (arg === '--output' || arg === '-o') {
|
||||
outputFile = args[i + 1];
|
||||
i++;
|
||||
} else {
|
||||
entities.push(arg);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.results || data.results.length === 0) {
|
||||
console.warn(`No results found for "${entity}".`);
|
||||
return {
|
||||
Entity: entity,
|
||||
Title: 'N/A',
|
||||
URL: 'N/A',
|
||||
Snippet: 'N/A',
|
||||
Score: 0
|
||||
};
|
||||
}
|
||||
|
||||
const topResult = data.results[0];
|
||||
return {
|
||||
Entity: entity,
|
||||
Title: topResult.title || 'N/A',
|
||||
URL: topResult.url || 'N/A',
|
||||
Snippet: topResult.snippet || 'N/A',
|
||||
Score: topResult.score || 0
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`Error fetching data for "${entity}":`, error);
|
||||
return null;
|
||||
}
|
||||
|
||||
return { entities, outputFile };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const results = [];
|
||||
for (const entity of ENTITIES) {
|
||||
const data = await fetchEntityData(entity);
|
||||
if (data) {
|
||||
results.push(data);
|
||||
const { entities, outputFile } = parseArgs();
|
||||
|
||||
if (entities.length !== 3) {
|
||||
console.error('Error: Exactly three entity names must be provided.');
|
||||
console.error('Usage: node src/index.js <entity1> <entity2> <entity3> [--output <file.md>]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
const results = await compareEntities(entities);
|
||||
const markdown = generateMarkdownTable(results);
|
||||
|
||||
console.log('\nGenerated Markdown Table:\n');
|
||||
console.log(markdown);
|
||||
|
||||
if (outputFile) {
|
||||
const filePath = path.resolve(process.cwd(), outputFile);
|
||||
fs.writeFileSync(filePath, markdown, 'utf-8');
|
||||
console.log(`\nMarkdown table written to ${filePath}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Fatal error: ${err.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
console.error('No data to display.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine the highest score for verdict
|
||||
const maxScore = Math.max(...results.map(r => r.Score));
|
||||
|
||||
// Add verdict column
|
||||
const tableData = results.map(r => ({
|
||||
Entity: r.Entity,
|
||||
Title: r.Title,
|
||||
URL: r.URL,
|
||||
Snippet: r.Snippet,
|
||||
Score: r.Score,
|
||||
Verdict: r.Score === maxScore ? 'Best' : ''
|
||||
}));
|
||||
|
||||
// Print table
|
||||
console.log('\nComparison Table (3xN with Verdict):\n');
|
||||
console.table(tableData);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,14 @@
|
||||
export function generateMarkdownTable(results) {
|
||||
const header = '| Entity | Summary |\n|---|---|';
|
||||
const rows = results
|
||||
.map(
|
||||
(r) =>
|
||||
`| ${escapeMarkdown(r.name)} | ${escapeMarkdown(r.summary)} |`
|
||||
)
|
||||
.join('\n');
|
||||
return `${header}\n${rows}`;
|
||||
}
|
||||
|
||||
function escapeMarkdown(text) {
|
||||
return text.replace(/\|/g, '\\|');
|
||||
}
|
||||
Reference in New Issue
Block a user