/** * ExaResearchTool - Agentic web research using Exa.ai Research API * * The Research API is an asynchronous, multi-step pipeline that transforms * open-ended questions into grounded reports with citations. The system performs * planning, searching, and reasoning to produce comprehensive research outputs. * * See: https://docs.exa.ai/reference/exa-research */ import { Tool } from './Tool.js'; import type { ToolInputs } from '../types.js'; export interface ExaResearchConfig { apiKey?: string; model?: 'exa-research-fast' | 'exa-research' | 'exa-research-pro'; pollInterval?: number; // Milliseconds between status checks (default: 2000) maxPollTime?: number; // Max time to poll in milliseconds (default: 300000 = 5 minutes) } interface ResearchResponse { researchId: string; createdAt: number; model: string; instructions: string; status: 'pending' | 'running' | 'completed' | 'failed' | 'canceled'; output?: { content: string; // Markdown report with citations parsed?: unknown; // Structured data if outputSchema provided }; costDollars?: { total: number; numSearches: number; numPages: number; reasoningTokens: number; }; finishedAt?: number; error?: string; events?: Array>; } export class ExaResearchTool extends Tool { readonly name = 'exa_research'; readonly description = 'Perform comprehensive web research using Exa.ai\'s agentic research system. Provide natural-language instructions about what to research, and the AI research agent will plan searches, gather sources, extract facts, and synthesize findings into a detailed markdown report with citations. Ideal for deep research on any topic. Results typically complete in 20-90 seconds.'; readonly inputs: ToolInputs = { instructions: { type: 'string', description: 'Natural-language task description of what to research (max 4096 characters). Be clear about what information you want, how research should be conducted, and what the output should contain.', required: true, }, model: { type: 'string', description: 'Research model: "exa-research-fast" (faster, cheaper), "exa-research" (balanced, default), or "exa-research-pro" (most thorough)', required: false, }, outputSchema: { type: 'object', description: 'Optional JSON Schema to enforce structured output format (max 8 root fields, 5 levels deep). If omitted, returns markdown report.', required: false, }, }; readonly outputType = 'string'; private apiKey: string; private defaultModel: string; private pollInterval: number; private maxPollTime: number; constructor(config?: ExaResearchConfig) { super(); this.apiKey = config?.apiKey ?? process.env.EXA_API_KEY ?? ''; this.defaultModel = config?.model ?? 'exa-research'; this.pollInterval = config?.pollInterval ?? 2000; // 2 seconds this.maxPollTime = config?.maxPollTime ?? 300000; // 5 minutes } async setup(): Promise { if (!this.apiKey) { throw new Error('EXA_API_KEY is required. Set it as an environment variable or pass it in the config.'); } this.isSetup = true; } async execute(args: Record): Promise { const instructions = args.instructions as string; const model = (args.model as string) ?? this.defaultModel; const outputSchema = args.outputSchema as Record | undefined; if (!instructions || instructions.length > 4096) { throw new Error('Instructions are required and must be <= 4096 characters'); } // Step 1: Create research task const createBody: Record = { instructions, model, }; if (outputSchema) { createBody.outputSchema = outputSchema; } const createResponse = await fetch('https://api.exa.ai/research/v1', { method: 'POST', headers: { 'x-api-key': this.apiKey, 'Content-Type': 'application/json', }, body: JSON.stringify(createBody), }); if (!createResponse.ok) { const errorText = await createResponse.text(); throw new Error(`Failed to create research task (${createResponse.status}): ${errorText}`); } const createData = await createResponse.json() as { researchId: string }; const researchId = createData.researchId; console.log(`Research task created: ${researchId}. Polling for results...`); // Step 2: Poll for completion const startTime = Date.now(); let attempts = 0; while (Date.now() - startTime < this.maxPollTime) { attempts++; // Wait before polling (except first attempt) if (attempts > 1) { await new Promise(resolve => setTimeout(resolve, this.pollInterval)); } const statusResponse = await fetch(`https://api.exa.ai/research/v1/${researchId}`, { method: 'GET', headers: { 'x-api-key': this.apiKey, }, }); if (!statusResponse.ok) { const errorText = await statusResponse.text(); throw new Error(`Failed to check research status (${statusResponse.status}): ${errorText}`); } const statusData = await statusResponse.json() as ResearchResponse; if (statusData.status === 'completed') { // Success! Return the research output const output = statusData.output; if (!output) { throw new Error('Research completed but no output was returned'); } // Format the response with cost information const sections: string[] = []; // Add the main content (markdown report or structured data) if (outputSchema && output.parsed) { sections.push('# Research Results (Structured)\n'); sections.push(JSON.stringify(output.parsed, null, 2)); } else { sections.push(output.content); } // Add cost breakdown if (statusData.costDollars) { const cost = statusData.costDollars; sections.push('\n---\n'); sections.push('## Research Metrics\n'); sections.push(`- **Cost**: $${cost.total.toFixed(4)}`); sections.push(`- **Searches**: ${cost.numSearches}`); sections.push(`- **Pages analyzed**: ${cost.numPages}`); sections.push(`- **Reasoning tokens**: ${cost.reasoningTokens.toLocaleString()}`); } console.log(`Research completed in ${attempts} polls (${((Date.now() - startTime) / 1000).toFixed(1)}s)`); return sections.join('\n'); } if (statusData.status === 'failed') { throw new Error(`Research failed: ${statusData.error ?? 'Unknown error'}`); } if (statusData.status === 'canceled') { throw new Error('Research was canceled'); } // Still pending or running, continue polling if (attempts % 10 === 0) { console.log(`Still researching... (${attempts} polls, ${((Date.now() - startTime) / 1000).toFixed(0)}s elapsed)`); } } throw new Error(`Research timed out after ${this.maxPollTime / 1000}s. Task ID: ${researchId}`); } }