1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
import { tavily } from '@tavily/core'; import type { SearchOptions, TavilyResponse, ISearchService } from './types.js';
export class TavilyClient implements ISearchService { private client: ReturnType<typeof tavily> | null = null; private apiKey: string; private available: boolean = true;
constructor(apiKey: string) { this.apiKey = apiKey;
if (!apiKey || apiKey.trim() === '' || apiKey.startsWith('your-')) { console.warn('[Tavily] API Key 未配置或无效'); this.available = false; return; }
try { this.client = tavily({ apiKey: this.apiKey }); console.log('[Tavily] 客户端初始化成功'); } catch (error) { console.error('[Tavily] 客户端初始化失败:', error); this.available = false; } }
isAvailable(): boolean { return this.available; }
async search(options: SearchOptions): Promise<TavilyResponse> { if (!this.available || !this.client) { throw new Error('Tavily 服务不可用'); }
console.log(`\n[Tavily] 搜索: "${options.query}"`); console.log(` 深度: ${options.searchDepth || 'basic'}`); console.log(` 结果数: ${options.maxResults || 5}`);
const response = await this.client.search(options.query, { maxResults: options.maxResults || 5, searchDepth: options.searchDepth || 'basic', includeAnswer: options.includeAnswer !== false, includeRawContent: options.includeRawContent ? 'markdown' : false, includeImages: options.includeImages || false, days: options.days, topic: options.topic, });
const result: TavilyResponse = { answer: response.answer || '', query: options.query, results: (response.results || []).map((item) => ({ title: item.title || '', url: item.url || '', content: item.content || '', score: item.score || 0, publishedDate: item.publishedDate, })), };
console.log(`[Tavily] 搜索完成,找到 ${result.results.length} 个结果\n`);
return result; } }
export function createTavilyClient(apiKey?: string): TavilyClient { const key = apiKey || process.env.TAVILY_API_KEY || ''; return new TavilyClient(key); }
|