valyu-js 2.5.3 → 2.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -305,7 +305,6 @@ The search method returns a `SearchResponse` object with the following structure
305
305
  web: number,
306
306
  proprietary: number
307
307
  },
308
- total_deduction_pcm: number, // Cost in CPM
309
308
  total_deduction_dollars: number, // Cost in dollars
310
309
  total_characters: number // Total characters returned
311
310
  }
package/dist/index.d.mts CHANGED
@@ -44,7 +44,6 @@ interface SearchResponse {
44
44
  web: number;
45
45
  proprietary: number;
46
46
  };
47
- total_deduction_pcm: number;
48
47
  total_deduction_dollars: number;
49
48
  total_characters: number;
50
49
  }
package/dist/index.d.ts CHANGED
@@ -44,7 +44,6 @@ interface SearchResponse {
44
44
  web: number;
45
45
  proprietary: number;
46
46
  };
47
- total_deduction_pcm: number;
48
47
  total_deduction_dollars: number;
49
48
  total_characters: number;
50
49
  }
package/dist/index.js CHANGED
@@ -180,7 +180,6 @@ var Valyu = class {
180
180
  query,
181
181
  results: [],
182
182
  results_by_source: { web: 0, proprietary: 0 },
183
- total_deduction_pcm: 0,
184
183
  total_deduction_dollars: 0,
185
184
  total_characters: 0
186
185
  };
@@ -193,7 +192,6 @@ var Valyu = class {
193
192
  query,
194
193
  results: [],
195
194
  results_by_source: { web: 0, proprietary: 0 },
196
- total_deduction_pcm: 0,
197
195
  total_deduction_dollars: 0,
198
196
  total_characters: 0
199
197
  };
@@ -206,7 +204,6 @@ var Valyu = class {
206
204
  query,
207
205
  results: [],
208
206
  results_by_source: { web: 0, proprietary: 0 },
209
- total_deduction_pcm: 0,
210
207
  total_deduction_dollars: 0,
211
208
  total_characters: 0
212
209
  };
@@ -220,7 +217,6 @@ var Valyu = class {
220
217
  query,
221
218
  results: [],
222
219
  results_by_source: { web: 0, proprietary: 0 },
223
- total_deduction_pcm: 0,
224
220
  total_deduction_dollars: 0,
225
221
  total_characters: 0
226
222
  };
@@ -234,7 +230,6 @@ var Valyu = class {
234
230
  query,
235
231
  results: [],
236
232
  results_by_source: { web: 0, proprietary: 0 },
237
- total_deduction_pcm: 0,
238
233
  total_deduction_dollars: 0,
239
234
  total_characters: 0
240
235
  };
@@ -252,7 +247,6 @@ var Valyu = class {
252
247
  query,
253
248
  results: [],
254
249
  results_by_source: { web: 0, proprietary: 0 },
255
- total_deduction_pcm: 0,
256
250
  total_deduction_dollars: 0,
257
251
  total_characters: 0
258
252
  };
@@ -267,7 +261,6 @@ var Valyu = class {
267
261
  query,
268
262
  results: [],
269
263
  results_by_source: { web: 0, proprietary: 0 },
270
- total_deduction_pcm: 0,
271
264
  total_deduction_dollars: 0,
272
265
  total_characters: 0
273
266
  };
@@ -285,7 +278,6 @@ var Valyu = class {
285
278
  query,
286
279
  results: [],
287
280
  results_by_source: { web: 0, proprietary: 0 },
288
- total_deduction_pcm: 0,
289
281
  total_deduction_dollars: 0,
290
282
  total_characters: 0
291
283
  };
@@ -339,7 +331,6 @@ var Valyu = class {
339
331
  query,
340
332
  results: [],
341
333
  results_by_source: { web: 0, proprietary: 0 },
342
- total_deduction_pcm: 0,
343
334
  total_deduction_dollars: 0,
344
335
  total_characters: 0
345
336
  };
@@ -353,7 +344,6 @@ var Valyu = class {
353
344
  query,
354
345
  results: [],
355
346
  results_by_source: { web: 0, proprietary: 0 },
356
- total_deduction_pcm: 0,
357
347
  total_deduction_dollars: 0,
358
348
  total_characters: 0
359
349
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @returns Promise resolving to content extraction results\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 10) {\n return {\n success: false,\n error: \"Maximum 10 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?api_key_id=${options.apiKeyId}&limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: fullContent || finalMetadata.contents || \"\",\n data_type: finalMetadata.data_type || \"unstructured\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n data_type: parsed.data_type,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentResult,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AA2CX,IAAM,QAAN,MAAY;AAAA,EA2DjB,YAAY,QAAiB,UAAkB,2BAA2B;AACxE,QAAI,CAAC,QAAQ;AACX,eAAS,QAAQ,IAAI;AACrB,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,MAAM,0BAA0B;AAAA,MAC5C;AAAA,IACF;AACA,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,MACb,gBAAgB;AAAA,MAChB,aAAa;AAAA,IACf;AAGA,SAAK,eAAe;AAAA,MAClB,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,cAAc,KAAK,0BAA0B,KAAK,IAAI;AAAA,MACtD,WAAW,KAAK,uBAAuB,KAAK,IAAI;AAAA,IAClD;AAGA,SAAK,QAAQ;AAAA,MACX,QAAQ,KAAK,aAAa,KAAK,IAAI;AAAA,MACnC,QAAQ,KAAK,aAAa,KAAK,IAAI;AAAA,MACnC,UAAU,KAAK,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":["import axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @returns Promise resolving to content extraction results\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 10) {\n return {\n success: false,\n error: \"Maximum 10 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?api_key_id=${options.apiKeyId}&limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: fullContent || finalMetadata.contents || \"\",\n data_type: finalMetadata.data_type || \"unstructured\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n data_type: parsed.data_type,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentResult,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AA2CX,IAAM,QAAN,MAAY;AAAA,EA2DjB,YAAY,QAAiB,UAAkB,2BAA2B;AACxE,QAAI,CAAC,QAAQ;AACX,eAAS,QAAQ,IAAI;AACrB,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,MAAM,0BAA0B;AAAA,MAC5C;AAAA,IACF;AACA,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,MACb,gBAAgB;AAAA,MAChB,aAAa;AAAA,IACf;AAGA,SAAK,eAAe;AAAA,MAClB,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,cAAc,KAAK,0BAA0B,KAAK,IAAI;AAAA,MACtD,WAAW,KAAK,uBAAuB,KAAK,IAAI;AAAA,IAClD;AAGA,SAAK,QAAQ;AAAA,MACX,QAAQ,KAAK,aAAa,KAAK,IAAI;AAAA,M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AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,OAAe,qBACb,OACkD;AAClD,UAAM,EAAE,MAAM,SAAS,MAAM;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAc,iBACZ,UAAkC,CAAC,GACD;AAClC,QAAI;AAEF,YAAM,SAAS,IAAI,gBAAgB;AACnC,UAAI,QAAQ,UAAU;AACpB,eAAO,OAAO,YAAY,QAAQ,QAAQ;AAAA,MAC5C;AAEA,YAAM,MAAM,GAAG,KAAK,OAAO,eACzB,OAAO,SAAS,IAAI,IAAI,OAAO,SAAS,CAAC,KAAK,EAChD;AACA,YAAM,WAAW,MAAM,aAAAD,QAAM,IAAI,KAAK,EAAE,SAAS,KAAK,QAAQ,CAAC;AAE/D,aAAO,EAAE,SAAS,MAAM,aAAa,SAAS,KAAK,YAAY;AAAA,IACjE,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,yBAAiE;AAC7E,QAAI;AACF,YAAM,WAAW,MAAM,aAAAA,QAAM,IAAI,GAAG,KAAK,OAAO,2BAA2B;AAAA,QACzE,SAAS,KAAK;AAAA,MAChB,CAAC;AAED,aAAO,EAAE,SAAS,MAAM,YAAY,SAAS,KAAK,WAAW;AAAA,IAC/D,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AACF;","names":["axios","response"]}
package/dist/index.mjs CHANGED
@@ -146,7 +146,6 @@ var Valyu = class {
146
146
  query,
147
147
  results: [],
148
148
  results_by_source: { web: 0, proprietary: 0 },
149
- total_deduction_pcm: 0,
150
149
  total_deduction_dollars: 0,
151
150
  total_characters: 0
152
151
  };
@@ -159,7 +158,6 @@ var Valyu = class {
159
158
  query,
160
159
  results: [],
161
160
  results_by_source: { web: 0, proprietary: 0 },
162
- total_deduction_pcm: 0,
163
161
  total_deduction_dollars: 0,
164
162
  total_characters: 0
165
163
  };
@@ -172,7 +170,6 @@ var Valyu = class {
172
170
  query,
173
171
  results: [],
174
172
  results_by_source: { web: 0, proprietary: 0 },
175
- total_deduction_pcm: 0,
176
173
  total_deduction_dollars: 0,
177
174
  total_characters: 0
178
175
  };
@@ -186,7 +183,6 @@ var Valyu = class {
186
183
  query,
187
184
  results: [],
188
185
  results_by_source: { web: 0, proprietary: 0 },
189
- total_deduction_pcm: 0,
190
186
  total_deduction_dollars: 0,
191
187
  total_characters: 0
192
188
  };
@@ -200,7 +196,6 @@ var Valyu = class {
200
196
  query,
201
197
  results: [],
202
198
  results_by_source: { web: 0, proprietary: 0 },
203
- total_deduction_pcm: 0,
204
199
  total_deduction_dollars: 0,
205
200
  total_characters: 0
206
201
  };
@@ -218,7 +213,6 @@ var Valyu = class {
218
213
  query,
219
214
  results: [],
220
215
  results_by_source: { web: 0, proprietary: 0 },
221
- total_deduction_pcm: 0,
222
216
  total_deduction_dollars: 0,
223
217
  total_characters: 0
224
218
  };
@@ -233,7 +227,6 @@ var Valyu = class {
233
227
  query,
234
228
  results: [],
235
229
  results_by_source: { web: 0, proprietary: 0 },
236
- total_deduction_pcm: 0,
237
230
  total_deduction_dollars: 0,
238
231
  total_characters: 0
239
232
  };
@@ -251,7 +244,6 @@ var Valyu = class {
251
244
  query,
252
245
  results: [],
253
246
  results_by_source: { web: 0, proprietary: 0 },
254
- total_deduction_pcm: 0,
255
247
  total_deduction_dollars: 0,
256
248
  total_characters: 0
257
249
  };
@@ -305,7 +297,6 @@ var Valyu = class {
305
297
  query,
306
298
  results: [],
307
299
  results_by_source: { web: 0, proprietary: 0 },
308
- total_deduction_pcm: 0,
309
300
  total_deduction_dollars: 0,
310
301
  total_characters: 0
311
302
  };
@@ -319,7 +310,6 @@ var Valyu = class {
319
310
  query,
320
311
  results: [],
321
312
  results_by_source: { web: 0, proprietary: 0 },
322
- total_deduction_pcm: 0,
323
313
  total_deduction_dollars: 0,
324
314
  total_characters: 0
325
315
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_pcm: 0.0,\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @returns Promise resolving to content extraction results\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 10) {\n return {\n success: false,\n error: \"Maximum 10 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?api_key_id=${options.apiKeyId}&limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: fullContent || finalMetadata.contents || \"\",\n data_type: finalMetadata.data_type || \"unstructured\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n data_type: parsed.data_type,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentResult,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";AAAA,OAAO,WAAW;AA2CX,IAAM,QAAN,MAAY;AAAA,EA2DjB,YAAY,QAAiB,UAAkB,2BAA2B;AACxE,QAAI,CAAC,QAAQ;AACX,eAAS,QAAQ,IAAI;AACrB,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,MAAM,0BAA0B;AAAA,MAC5C;AAAA,IACF;AACA,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,MACb,gBAAgB;AAAA,MAChB,aAAa;AAAA,IACf;AAGA,SAAK,eAAe;AAAA,MAClB,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KA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CAAC;AAED,aAAO,EAAE,SAAS,MAAM,YAAY,SAAS,KAAK,WAAW;AAAA,IAC/D,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AACF;","names":["response"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import axios from \"axios\";\nimport {\n SearchResponse,\n SearchType,\n SearchOptions,\n ContentsOptions,\n ContentsResponse,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerStreamChunk,\n SearchResult,\n DeepResearchCreateOptions,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n CreateBatchOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksOptions,\n AddBatchTasksResponse,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DeepResearchBatch,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n\n// Valyu API client\nexport class Valyu {\n private baseUrl: string;\n private headers: Record<string, string>;\n\n // DeepResearch namespace\n public deepresearch: {\n create: (\n options: DeepResearchCreateOptions\n ) => Promise<DeepResearchCreateResponse>;\n status: (taskId: string) => Promise<DeepResearchStatusResponse>;\n wait: (\n taskId: string,\n options?: WaitOptions\n ) => Promise<DeepResearchStatusResponse>;\n stream: (taskId: string, callback: StreamCallback) => Promise<void>;\n list: (options: ListOptions) => Promise<DeepResearchListResponse>;\n update: (\n taskId: string,\n instruction: string\n ) => Promise<DeepResearchUpdateResponse>;\n cancel: (taskId: string) => Promise<DeepResearchCancelResponse>;\n delete: (taskId: string) => Promise<DeepResearchDeleteResponse>;\n togglePublic: (\n taskId: string,\n isPublic: boolean\n ) => Promise<DeepResearchTogglePublicResponse>;\n getAssets: (\n taskId: string,\n assetId: string,\n options?: DeepResearchGetAssetsOptions\n ) => Promise<DeepResearchGetAssetsResponse>;\n };\n\n // Batch API namespace\n public batch: {\n create: (options?: CreateBatchOptions) => Promise<CreateBatchResponse>;\n status: (batchId: string) => Promise<BatchStatusResponse>;\n addTasks: (\n batchId: string,\n options: AddBatchTasksOptions\n ) => Promise<AddBatchTasksResponse>;\n listTasks: (\n batchId: string,\n options?: ListBatchTasksOptions\n ) => Promise<ListBatchTasksResponse>;\n cancel: (batchId: string) => Promise<CancelBatchResponse>;\n list: (options?: ListBatchesOptions) => Promise<ListBatchesResponse>;\n waitForCompletion: (\n batchId: string,\n options?: BatchWaitOptions\n ) => Promise<DeepResearchBatch>;\n };\n\n // Datasources API namespace\n public datasources: {\n list: (options?: DatasourcesListOptions) => Promise<DatasourcesListResponse>;\n categories: () => Promise<DatasourcesCategoriesResponse>;\n };\n\n constructor(apiKey?: string, baseUrl: string = \"https://api.valyu.ai/v1\") {\n if (!apiKey) {\n apiKey = process.env.VALYU_API_KEY;\n if (!apiKey) {\n throw new Error(\"VALYU_API_KEY is not set\");\n }\n }\n this.baseUrl = baseUrl;\n this.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n\n // Initialize DeepResearch namespace\n this.deepresearch = {\n create: this._deepresearchCreate.bind(this),\n status: this._deepresearchStatus.bind(this),\n wait: this._deepresearchWait.bind(this),\n stream: this._deepresearchStream.bind(this),\n list: this._deepresearchList.bind(this),\n update: this._deepresearchUpdate.bind(this),\n cancel: this._deepresearchCancel.bind(this),\n delete: this._deepresearchDelete.bind(this),\n togglePublic: this._deepresearchTogglePublic.bind(this),\n getAssets: this._deepresearchGetAssets.bind(this),\n };\n\n // Initialize Batch namespace\n this.batch = {\n create: this._batchCreate.bind(this),\n status: this._batchStatus.bind(this),\n addTasks: this._batchAddTasks.bind(this),\n listTasks: this._batchListTasks.bind(this),\n cancel: this._batchCancel.bind(this),\n list: this._batchList.bind(this),\n waitForCompletion: this._batchWaitForCompletion.bind(this),\n };\n\n // Initialize Datasources namespace\n this.datasources = {\n list: this._datasourcesList.bind(this),\n categories: this._datasourcesCategories.bind(this),\n };\n }\n\n /**\n * Validates date format (YYYY-MM-DD)\n */\n private validateDateFormat(date: string): boolean {\n const dateRegex = /^\\d{4}-\\d{2}-\\d{2}$/;\n if (!dateRegex.test(date)) {\n return false;\n }\n const parsedDate = new Date(date);\n return parsedDate instanceof Date && !isNaN(parsedDate.getTime());\n }\n\n /**\n * Validates if a string is a valid URL\n */\n private validateUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Validates if a string is a valid domain (with optional path)\n */\n private validateDomain(domain: string): boolean {\n // Domain must have at least one dot and valid structure\n // Supports: example.com, example.com/path, subdomain.example.com/path/to/resource\n const domainRegex =\n /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\\/.+)?$/;\n return domainRegex.test(domain);\n }\n\n /**\n * Validates if a string is a valid dataset identifier (provider/datasetname)\n */\n private validateDatasetId(datasetId: string): boolean {\n // Dataset format: provider/datasetname (exactly one slash)\n // Provider and dataset name can contain alphanumeric, hyphens, underscores\n const parts = datasetId.split(\"/\");\n if (parts.length !== 2) return false;\n\n const providerRegex = /^[a-zA-Z0-9_-]+$/;\n const datasetRegex = /^[a-zA-Z0-9_-]+$/;\n\n return (\n providerRegex.test(parts[0]) &&\n datasetRegex.test(parts[1]) &&\n parts[0].length > 0 &&\n parts[1].length > 0\n );\n }\n\n /**\n * Validates source strings (domains, URLs, or dataset IDs)\n */\n private validateSource(source: string): boolean {\n // Check if it's a valid URL\n if (this.validateUrl(source)) {\n return true;\n }\n\n // Check if it's a valid domain (with optional path)\n if (this.validateDomain(source)) {\n return true;\n }\n\n // Check if it's a valid dataset identifier\n if (this.validateDatasetId(source)) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Validates an array of source strings\n */\n private validateSources(sources: string[]): {\n valid: boolean;\n invalidSources: string[];\n } {\n const invalidSources: string[] = [];\n\n for (const source of sources) {\n if (!this.validateSource(source)) {\n invalidSources.push(source);\n }\n }\n\n return {\n valid: invalidSources.length === 0,\n invalidSources,\n };\n }\n\n /**\n * Search for information using the Valyu DeepSearch API\n * @param query - The search query string\n * @param options - Search configuration options\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.maxNumResults - Maximum number of results (1-100)\n * @param options.maxPrice - Maximum price per thousand characters (CPM)\n * @param options.isToolCall - Whether this is a tool call\n * @param options.relevanceThreshold - Minimum relevance score (0-1)\n * @param options.includedSources - List of specific sources to include\n * @param options.excludeSources - List of URLs/domains to exclude from search results\n * @param options.category - Category filter for search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.countryCode - Country code filter for search results\n * @param options.responseLength - Response content length: \"short\"/\"medium\"/\"large\"/\"max\" or integer character count\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.urlOnly - Returns shortened snippets (default: false)\n * @returns Promise resolving to search results\n */\n async search(\n query: string,\n options: SearchOptions = {}\n ): Promise<SearchResponse> {\n try {\n // Default values\n const defaultSearchType: SearchType = \"all\";\n const defaultMaxNumResults = 10;\n const defaultIsToolCall = true;\n const defaultRelevanceThreshold = 0.5;\n\n // Validate searchType\n let finalSearchType: SearchType = defaultSearchType;\n const providedSearchTypeString = options.searchType?.toLowerCase();\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n } else if (options.searchType !== undefined) {\n return {\n success: false,\n error:\n \"Invalid searchType provided. Must be one of: all, web, proprietary, news\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return {\n success: false,\n error: \"Invalid startDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return {\n success: false,\n error: \"Invalid endDate format. Must be YYYY-MM-DD\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate maxNumResults range\n const maxNumResults = options.maxNumResults ?? defaultMaxNumResults;\n if (maxNumResults < 1 || maxNumResults > 100) {\n return {\n success: false,\n error: \"maxNumResults must be between 1 and 100\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n // Validate includedSources format\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return {\n success: false,\n error: \"includedSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const includedSourcesValidation = this.validateSources(\n options.includedSources\n );\n if (!includedSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Validate excludeSources format\n if (options.excludeSources !== undefined) {\n if (!Array.isArray(options.excludeSources)) {\n return {\n success: false,\n error: \"excludeSources must be an array\",\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n const excludeSourcesValidation = this.validateSources(\n options.excludeSources\n );\n if (!excludeSourcesValidation.valid) {\n return {\n success: false,\n error: `Invalid excludeSources format. Invalid sources: ${excludeSourcesValidation.invalidSources.join(\n \", \"\n )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n query,\n search_type: finalSearchType,\n max_num_results: maxNumResults,\n is_tool_call: options.isToolCall ?? defaultIsToolCall,\n relevance_threshold:\n options.relevanceThreshold ?? defaultRelevanceThreshold,\n };\n\n // Add maxPrice only if explicitly provided\n if (options.maxPrice !== undefined) {\n payload.max_price = options.maxPrice;\n }\n\n // Add optional parameters only if provided\n if (options.includedSources !== undefined) {\n payload.included_sources = options.includedSources;\n }\n\n if (options.excludeSources !== undefined) {\n payload.exclude_sources = options.excludeSources;\n }\n\n if (options.category !== undefined) {\n payload.category = options.category;\n }\n\n if (options.startDate !== undefined) {\n payload.start_date = options.startDate;\n }\n\n if (options.endDate !== undefined) {\n payload.end_date = options.endDate;\n }\n\n if (options.countryCode !== undefined) {\n payload.country_code = options.countryCode;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.fastMode !== undefined) {\n payload.fast_mode = options.fastMode;\n }\n\n if (options.urlOnly !== undefined) {\n payload.url_only = options.urlOnly;\n }\n\n const response = await axios.post(`${this.baseUrl}/deepsearch`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n tx_id: null,\n query,\n results: [],\n results_by_source: { web: 0, proprietary: 0 },\n total_deduction_dollars: 0.0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * Extract content from URLs with optional AI processing\n * @param urls - Array of URLs to process (max 10)\n * @param options - Content extraction configuration options\n * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema\n * @param options.extractEffort - Extraction thoroughness: \"normal\", \"high\", or \"auto\"\n * @param options.responseLength - Content length per URL\n * @param options.maxPriceDollars - Maximum cost limit in USD\n * @param options.screenshot - Request page screenshots (default: false)\n * @returns Promise resolving to content extraction results\n */\n async contents(\n urls: string[],\n options: ContentsOptions = {}\n ): Promise<ContentsResponse> {\n try {\n // Validate URLs array\n if (!urls || !Array.isArray(urls)) {\n return {\n success: false,\n error: \"urls must be an array\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length === 0) {\n return {\n success: false,\n error: \"urls array cannot be empty\",\n urls_requested: 0,\n urls_processed: 0,\n urls_failed: 0,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n if (urls.length > 10) {\n return {\n success: false,\n error: \"Maximum 10 URLs allowed per request\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate extractEffort if provided\n if (\n options.extractEffort &&\n ![\"normal\", \"high\", \"auto\"].includes(options.extractEffort)\n ) {\n return {\n success: false,\n error: \"extractEffort must be 'normal', 'high', or 'auto'\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n // Validate responseLength if provided\n if (options.responseLength !== undefined) {\n const validLengths = [\"short\", \"medium\", \"large\", \"max\"];\n if (\n typeof options.responseLength === \"string\" &&\n !validLengths.includes(options.responseLength)\n ) {\n return {\n success: false,\n error:\n \"responseLength must be 'short', 'medium', 'large', 'max', or a number\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n if (\n typeof options.responseLength === \"number\" &&\n options.responseLength <= 0\n ) {\n return {\n success: false,\n error: \"responseLength number must be positive\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n // Build payload with snake_case for API\n const payload: Record<string, any> = {\n urls,\n };\n\n // Add optional parameters only if provided\n if (options.summary !== undefined) {\n payload.summary = options.summary;\n }\n\n if (options.extractEffort !== undefined) {\n payload.extract_effort = options.extractEffort;\n }\n\n if (options.responseLength !== undefined) {\n payload.response_length = options.responseLength;\n }\n\n if (options.maxPriceDollars !== undefined) {\n payload.max_price_dollars = options.maxPriceDollars;\n }\n\n if (options.screenshot !== undefined) {\n payload.screenshot = options.screenshot;\n }\n\n const response = await axios.post(`${this.baseUrl}/contents`, payload, {\n headers: this.headers,\n });\n\n if (!response.status || response.status < 200 || response.status >= 300) {\n return {\n success: false,\n error: response.data?.error || \"Request failed\",\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n\n return response.data;\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n urls_requested: urls.length,\n urls_processed: 0,\n urls_failed: urls.length,\n results: [],\n total_cost_dollars: 0,\n total_characters: 0,\n };\n }\n }\n\n /**\n * DeepResearch: Create a new research task\n * @param options.search - Search configuration options\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n */\n private async _deepresearchCreate(\n options: DeepResearchCreateOptions\n ): Promise<DeepResearchCreateResponse> {\n try {\n // Use query field (input is supported for backward compatibility)\n const queryValue = options.query ?? options.input;\n\n // Validation\n if (!queryValue?.trim()) {\n return {\n success: false,\n error: \"query is required and cannot be empty\",\n };\n }\n\n // Build payload with snake_case\n // Prefer mode over model (backward compatible)\n const mode = options.mode ?? options.model;\n const payload: Record<string, any> = {\n query: queryValue,\n mode: mode || \"fast\", // API defaults to \"standard\", but we keep \"fast\" for backward compatibility\n output_formats: options.outputFormats || [\"markdown\"],\n code_execution: options.codeExecution !== false,\n };\n\n // Add optional fields\n if (options.strategy) payload.strategy = options.strategy;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.urls) payload.urls = options.urls;\n if (options.files) payload.files = options.files;\n if (options.deliverables) payload.deliverables = options.deliverables;\n if (options.mcpServers) payload.mcp_servers = options.mcpServers;\n if (options.previousReports) {\n payload.previous_reports = options.previousReports;\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.brandCollectionId)\n payload.brand_collection_id = options.brandCollectionId;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task status\n */\n private async _deepresearchStatus(\n taskId: string\n ): Promise<DeepResearchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/status`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Wait for task completion with polling\n */\n private async _deepresearchWait(\n taskId: string,\n options: WaitOptions = {}\n ): Promise<DeepResearchStatusResponse> {\n const pollInterval = options.pollInterval || 5000;\n const maxWaitTime = options.maxWaitTime || 7200000;\n const startTime = Date.now();\n\n while (true) {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n throw new Error(status.error);\n }\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(status);\n }\n\n // Terminal states\n if (\n status.status === \"completed\" ||\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n return status;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * DeepResearch: Stream real-time updates\n */\n private async _deepresearchStream(\n taskId: string,\n callback: StreamCallback\n ): Promise<void> {\n let isComplete = false;\n let lastMessageCount = 0;\n\n while (!isComplete) {\n try {\n const status = await this._deepresearchStatus(taskId);\n\n if (!status.success) {\n if (callback.onError) {\n callback.onError(new Error(status.error));\n }\n return;\n }\n\n // Progress updates\n if (status.progress && callback.onProgress) {\n callback.onProgress(\n status.progress.current_step,\n status.progress.total_steps\n );\n }\n\n // New messages\n if (status.messages && callback.onMessage) {\n const newMessages = status.messages.slice(lastMessageCount);\n newMessages.forEach((msg) => callback.onMessage!(msg));\n lastMessageCount = status.messages.length;\n }\n\n // Terminal states\n if (status.status === \"completed\") {\n if (callback.onComplete) {\n callback.onComplete(status);\n }\n isComplete = true;\n } else if (\n status.status === \"failed\" ||\n status.status === \"cancelled\"\n ) {\n if (callback.onError) {\n callback.onError(\n new Error(status.error || `Task ${status.status}`)\n );\n }\n isComplete = true;\n }\n\n if (!isComplete) {\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n } catch (error: any) {\n if (callback.onError) {\n callback.onError(error);\n }\n throw error;\n }\n }\n }\n\n /**\n * DeepResearch: List all tasks\n */\n private async _deepresearchList(\n options: ListOptions\n ): Promise<DeepResearchListResponse> {\n try {\n const limit = options.limit || 10;\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/list?api_key_id=${options.apiKeyId}&limit=${limit}`,\n { headers: this.headers }\n );\n\n return { success: true, data: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Add follow-up instruction\n */\n private async _deepresearchUpdate(\n taskId: string,\n instruction: string\n ): Promise<DeepResearchUpdateResponse> {\n try {\n if (!instruction?.trim()) {\n return {\n success: false,\n error: \"instruction is required and cannot be empty\",\n };\n }\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/update`,\n { instruction },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Cancel task\n */\n private async _deepresearchCancel(\n taskId: string\n ): Promise<DeepResearchCancelResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Delete task\n */\n private async _deepresearchDelete(\n taskId: string\n ): Promise<DeepResearchDeleteResponse> {\n try {\n const response = await axios.delete(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/delete`,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Toggle public flag\n */\n private async _deepresearchTogglePublic(\n taskId: string,\n isPublic: boolean\n ): Promise<DeepResearchTogglePublicResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/tasks/${taskId}/public`,\n { public: isPublic },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * DeepResearch: Get task assets (images, deliverables, PDFs)\n */\n private async _deepresearchGetAssets(\n taskId: string,\n assetId: string,\n options: DeepResearchGetAssetsOptions = {}\n ): Promise<DeepResearchGetAssetsResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.token) {\n params.append(\"token\", options.token);\n }\n\n // Build headers - use API key if no token provided\n const headers: Record<string, string> = {};\n if (!options.token) {\n headers[\"x-api-key\"] = this.headers[\"x-api-key\"];\n }\n\n const url = `${\n this.baseUrl\n }/deepresearch/tasks/${taskId}/assets/${assetId}${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n\n const response = await axios.get(url, {\n headers,\n responseType: \"arraybuffer\", // For binary data\n });\n\n return {\n success: true,\n data: Buffer.from(response.data),\n contentType:\n response.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Create a new batch\n * @param options - Batch configuration options\n * @param options.name - Optional name for the batch\n * @param options.model - DeepResearch mode: \"fast\", \"standard\", or \"heavy\" (default: \"standard\")\n * @param options.outputFormats - Output formats for tasks (default: [\"markdown\"])\n * @param options.search - Search configuration for all tasks in batch\n * @param options.search.searchType - Type of search: \"all\", \"web\", or \"proprietary\" (default: \"all\")\n * @param options.search.includedSources - Array of source types to include (e.g., [\"academic\", \"finance\", \"web\"])\n * @param options.search.excludedSources - Array of source types to exclude (e.g., [\"web\", \"patent\"])\n * @param options.search.startDate - Start date filter in ISO format (YYYY-MM-DD)\n * @param options.search.endDate - End date filter in ISO format (YYYY-MM-DD)\n * @param options.search.category - Category filter for search results\n * @param options.webhookUrl - Optional HTTPS URL for completion notification\n * @param options.metadata - Optional metadata key-value pairs\n * @returns Promise resolving to batch creation response with batch_id and webhook_secret\n */\n private async _batchCreate(\n options: CreateBatchOptions = {}\n ): Promise<CreateBatchResponse> {\n try {\n const payload: Record<string, any> = {};\n\n if (options.name) payload.name = options.name;\n // Accept both mode (preferred) and model (backward compatible)\n const mode = options.mode ?? options.model;\n if (mode) payload.mode = mode;\n if (options.outputFormats) payload.output_formats = options.outputFormats;\n if (options.search) {\n payload.search = {};\n if (options.search.searchType) {\n payload.search.search_type = options.search.searchType;\n }\n if (options.search.includedSources) {\n payload.search.included_sources = options.search.includedSources;\n }\n if (options.search.excludedSources) {\n payload.search.excluded_sources = options.search.excludedSources;\n }\n if (options.search.startDate) {\n payload.search.start_date = options.search.startDate;\n }\n if (options.search.endDate) {\n payload.search.end_date = options.search.endDate;\n }\n if (options.search.category) {\n payload.search.category = options.search.category;\n }\n }\n if (options.webhookUrl) payload.webhook_url = options.webhookUrl;\n if (options.metadata) payload.metadata = options.metadata;\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches`,\n payload,\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Get batch status\n * @param batchId - The batch ID to query\n * @returns Promise resolving to batch status with counts and usage\n */\n private async _batchStatus(batchId: string): Promise<BatchStatusResponse> {\n try {\n const response = await axios.get(\n `${this.baseUrl}/deepresearch/batches/${batchId}`,\n { headers: this.headers }\n );\n\n return { success: true, batch: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Add tasks to a batch\n * @param batchId - The batch ID to add tasks to\n * @param options - Task configuration options\n * @param options.tasks - Array of task inputs (use 'query' field for each task)\n * @returns Promise resolving to response with added, tasks array, counts, and batch_id\n */\n private async _batchAddTasks(\n batchId: string,\n options: AddBatchTasksOptions\n ): Promise<AddBatchTasksResponse> {\n try {\n if (!options.tasks || !Array.isArray(options.tasks)) {\n return {\n success: false,\n error: \"tasks must be an array\",\n };\n }\n\n if (options.tasks.length === 0) {\n return {\n success: false,\n error: \"tasks array cannot be empty\",\n };\n }\n\n if (options.tasks.length > 100) {\n return {\n success: false,\n error: \"Maximum 100 tasks allowed per request\",\n };\n }\n\n // Validate that each task has a query\n for (const task of options.tasks) {\n if (!task.query && !task.input) {\n return {\n success: false,\n error: \"Each task must have a 'query' field\",\n };\n }\n }\n\n // Convert tasks to snake_case format for API\n // Note: Tasks can only include: id, query, strategy, urls, metadata\n // Tasks inherit model, output_formats, and search_params from batch\n const tasksPayload = options.tasks.map((task) => {\n const taskPayload: Record<string, any> = {};\n\n // Use query field (input is supported for backward compatibility)\n const queryValue = task.query ?? task.input;\n if (queryValue) {\n taskPayload.query = queryValue;\n }\n\n if (task.id) taskPayload.id = task.id;\n if (task.strategy) taskPayload.strategy = task.strategy;\n if (task.urls) taskPayload.urls = task.urls;\n if (task.metadata) taskPayload.metadata = task.metadata;\n\n return taskPayload;\n });\n\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,\n { tasks: tasksPayload },\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all tasks in a batch\n * @param batchId - The batch ID to query\n * @param options - Optional pagination and filtering options\n * @param options.status - Filter by status: \"queued\", \"running\", \"completed\", \"failed\", or \"cancelled\"\n * @param options.limit - Maximum number of tasks to return\n * @param options.lastKey - Pagination token from previous response\n * @returns Promise resolving to list of tasks with their status and pagination info\n */\n private async _batchListTasks(\n batchId: string,\n options: ListBatchTasksOptions = {}\n ): Promise<ListBatchTasksResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.status) {\n params.append(\"status\", options.status);\n }\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n if (options.lastKey) {\n params.append(\"last_key\", options.lastKey);\n }\n\n const url = `${this.baseUrl}/deepresearch/batches/${batchId}/tasks${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Cancel a batch and all its pending tasks\n * @param batchId - The batch ID to cancel\n * @returns Promise resolving to cancellation confirmation\n */\n private async _batchCancel(batchId: string): Promise<CancelBatchResponse> {\n try {\n const response = await axios.post(\n `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,\n {},\n { headers: this.headers }\n );\n\n return { success: true, ...response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: List all batches\n * @param options - Optional options\n * @param options.limit - Maximum number of batches to return\n * @returns Promise resolving to list of all batches\n */\n private async _batchList(\n options: ListBatchesOptions = {}\n ): Promise<ListBatchesResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.limit !== undefined) {\n params.append(\"limit\", options.limit.toString());\n }\n\n const url = `${this.baseUrl}/deepresearch/batches${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, {\n headers: this.headers,\n });\n\n return { success: true, batches: response.data };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Batch: Wait for batch completion with polling\n * @param batchId - The batch ID to wait for\n * @param options - Wait configuration options\n * @param options.pollInterval - Polling interval in milliseconds (default: 10000)\n * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)\n * @param options.onProgress - Callback for progress updates\n * @returns Promise resolving to final batch status\n */\n private async _batchWaitForCompletion(\n batchId: string,\n options: BatchWaitOptions = {}\n ): Promise<DeepResearchBatch> {\n const pollInterval = options.pollInterval || 10000; // 10 seconds default\n const maxWaitTime = options.maxWaitTime || 7200000; // 2 hours default\n const startTime = Date.now();\n\n while (true) {\n const statusResponse = await this._batchStatus(batchId);\n\n if (!statusResponse.success || !statusResponse.batch) {\n throw new Error(statusResponse.error || \"Failed to get batch status\");\n }\n\n const batch = statusResponse.batch;\n\n // Notify progress callback\n if (options.onProgress) {\n options.onProgress(batch);\n }\n\n // Terminal states\n if (\n batch.status === \"completed\" ||\n batch.status === \"completed_with_errors\" ||\n batch.status === \"cancelled\"\n ) {\n return batch;\n }\n\n // Check timeout\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error(\"Maximum wait time exceeded\");\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Get AI-powered answers using the Valyu Answer API\n * @param query - The question or query string\n * @param options - Answer configuration options\n * @param options.structuredOutput - JSON Schema object for structured responses\n * @param options.systemInstructions - Custom system-level instructions (max 2000 chars)\n * @param options.searchType - Type of search: \"web\", \"proprietary\", \"all\", or \"news\"\n * @param options.dataMaxPrice - Maximum spend (USD) for data retrieval\n * @param options.countryCode - Country code filter for search results\n * @param options.includedSources - List of specific sources to include\n * @param options.excludedSources - List of URLs/domains to exclude from search results\n * @param options.startDate - Start date filter (YYYY-MM-DD format)\n * @param options.endDate - End date filter (YYYY-MM-DD format)\n * @param options.fastMode - Fast mode for quicker but shorter results (default: false)\n * @param options.streaming - Enable streaming mode (default: false)\n * @returns Promise resolving to answer response, or AsyncGenerator for streaming\n */\n async answer(\n query: string,\n options: AnswerOptions = {}\n ): Promise<\n AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>\n > {\n // Validate inputs first\n const validationError = this.validateAnswerParams(query, options);\n if (validationError) {\n if (options.streaming) {\n return this.createErrorGenerator(validationError);\n }\n return { success: false, error: validationError };\n }\n\n const payload = this.buildAnswerPayload(query, options);\n\n if (options.streaming) {\n return this.streamAnswer(payload);\n } else {\n return this.fetchAnswer(payload);\n }\n }\n\n /**\n * Validate answer parameters\n */\n private validateAnswerParams(\n query: string,\n options: AnswerOptions\n ): string | null {\n // Validate query\n if (!query || typeof query !== \"string\" || query.trim().length === 0) {\n return \"Query is required and must be a non-empty string\";\n }\n\n // Validate searchType\n const providedSearchTypeString = options.searchType?.toLowerCase();\n if (\n providedSearchTypeString !== undefined &&\n providedSearchTypeString !== \"web\" &&\n providedSearchTypeString !== \"proprietary\" &&\n providedSearchTypeString !== \"all\" &&\n providedSearchTypeString !== \"news\"\n ) {\n return \"Invalid searchType provided. Must be one of: all, web, proprietary, news\";\n }\n\n // Validate systemInstructions\n if (options.systemInstructions !== undefined) {\n if (typeof options.systemInstructions !== \"string\") {\n return \"systemInstructions must be a string\";\n }\n const trimmed = options.systemInstructions.trim();\n if (trimmed.length === 0) {\n return \"systemInstructions cannot be empty when provided\";\n }\n if (trimmed.length > 2000) {\n return \"systemInstructions must be 2000 characters or less\";\n }\n }\n\n // Validate dataMaxPrice\n if (options.dataMaxPrice !== undefined) {\n if (\n typeof options.dataMaxPrice !== \"number\" ||\n options.dataMaxPrice <= 0\n ) {\n return \"dataMaxPrice must be a positive number\";\n }\n }\n\n // Validate date formats\n if (options.startDate && !this.validateDateFormat(options.startDate)) {\n return \"Invalid startDate format. Must be YYYY-MM-DD\";\n }\n if (options.endDate && !this.validateDateFormat(options.endDate)) {\n return \"Invalid endDate format. Must be YYYY-MM-DD\";\n }\n if (options.startDate && options.endDate) {\n const startDate = new Date(options.startDate);\n const endDate = new Date(options.endDate);\n if (startDate > endDate) {\n return \"startDate must be before endDate\";\n }\n }\n\n // Validate sources\n if (options.includedSources !== undefined) {\n if (!Array.isArray(options.includedSources)) {\n return \"includedSources must be an array\";\n }\n const validation = this.validateSources(options.includedSources);\n if (!validation.valid) {\n return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n if (options.excludedSources !== undefined) {\n if (!Array.isArray(options.excludedSources)) {\n return \"excludedSources must be an array\";\n }\n const validation = this.validateSources(options.excludedSources);\n if (!validation.valid) {\n return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(\n \", \"\n )}.`;\n }\n }\n\n return null;\n }\n\n /**\n * Build payload for answer API\n */\n private buildAnswerPayload(\n query: string,\n options: AnswerOptions\n ): Record<string, any> {\n const defaultSearchType: SearchType = \"all\";\n const providedSearchTypeString = options.searchType?.toLowerCase();\n let finalSearchType: SearchType = defaultSearchType;\n\n if (\n providedSearchTypeString === \"web\" ||\n providedSearchTypeString === \"proprietary\" ||\n providedSearchTypeString === \"all\" ||\n providedSearchTypeString === \"news\"\n ) {\n finalSearchType = providedSearchTypeString as SearchType;\n }\n\n const payload: Record<string, any> = {\n query: query.trim(),\n search_type: finalSearchType,\n };\n\n if (options.dataMaxPrice !== undefined)\n payload.data_max_price = options.dataMaxPrice;\n if (options.structuredOutput !== undefined)\n payload.structured_output = options.structuredOutput;\n if (options.systemInstructions !== undefined)\n payload.system_instructions = options.systemInstructions.trim();\n if (options.countryCode !== undefined)\n payload.country_code = options.countryCode;\n if (options.includedSources !== undefined)\n payload.included_sources = options.includedSources;\n if (options.excludedSources !== undefined)\n payload.excluded_sources = options.excludedSources;\n if (options.startDate !== undefined) payload.start_date = options.startDate;\n if (options.endDate !== undefined) payload.end_date = options.endDate;\n if (options.fastMode !== undefined) payload.fast_mode = options.fastMode;\n\n return payload;\n }\n\n /**\n * Fetch answer (non-streaming mode)\n */\n private async fetchAnswer(\n payload: Record<string, any>\n ): Promise<AnswerResponse> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n }\n\n // Collect streamed data into final response\n let fullContent = \"\";\n let searchResults: SearchResult[] = [];\n let finalMetadata: any = {};\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (reader) {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && !parsed.success) {\n searchResults = [...searchResults, ...parsed.search_results];\n }\n // Handle content chunks\n else if (parsed.choices) {\n const content = parsed.choices[0]?.delta?.content || \"\";\n if (content) fullContent += content;\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n finalMetadata = parsed;\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n // Build final response\n if (finalMetadata.success) {\n const finalSearchResults =\n finalMetadata.search_results || searchResults;\n const response: AnswerSuccessResponse = {\n success: true,\n tx_id: finalMetadata.tx_id || \"\",\n original_query: finalMetadata.original_query || payload.query,\n contents: fullContent || finalMetadata.contents || \"\",\n data_type: finalMetadata.data_type || \"unstructured\",\n search_results: finalSearchResults,\n search_metadata: finalMetadata.search_metadata || {\n tx_ids: [],\n number_of_results: 0,\n total_characters: 0,\n },\n ai_usage: finalMetadata.ai_usage || {\n input_tokens: 0,\n output_tokens: 0,\n },\n cost: finalMetadata.cost || {\n total_deduction_dollars: 0,\n search_deduction_dollars: 0,\n ai_deduction_dollars: 0,\n },\n };\n if (finalMetadata.extraction_metadata) {\n response.extraction_metadata = finalMetadata.extraction_metadata;\n }\n return response;\n }\n\n return {\n success: false,\n error: finalMetadata.error || \"Unknown error occurred\",\n };\n } catch (e: any) {\n return {\n success: false,\n error: e.message || \"Request failed\",\n };\n }\n }\n\n /**\n * Stream answer using SSE\n */\n private async *streamAnswer(\n payload: Record<string, any>\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n try {\n const response = await fetch(`${this.baseUrl}/answer`, {\n method: \"POST\",\n headers: {\n ...this.headers,\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n yield {\n type: \"error\",\n error: errorData.error || `HTTP Error: ${response.status}`,\n };\n return;\n }\n\n const reader = response.body?.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" };\n return;\n }\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const dataStr = line.slice(6);\n\n if (dataStr === \"[DONE]\") {\n yield { type: \"done\" };\n continue;\n }\n\n try {\n const parsed = JSON.parse(dataStr);\n\n // Handle search results\n if (parsed.search_results && parsed.success === undefined) {\n yield {\n type: \"search_results\",\n search_results: parsed.search_results,\n };\n }\n // Handle content chunks\n else if (parsed.choices) {\n const delta = parsed.choices[0]?.delta || {};\n const content = delta.content || \"\";\n const finishReason = parsed.choices[0]?.finish_reason;\n\n if (content || finishReason) {\n yield { type: \"content\", content, finish_reason: finishReason };\n }\n }\n // Handle final metadata\n else if (parsed.success !== undefined) {\n yield {\n type: \"metadata\",\n tx_id: parsed.tx_id,\n original_query: parsed.original_query,\n data_type: parsed.data_type,\n search_results: parsed.search_results,\n search_metadata: parsed.search_metadata,\n ai_usage: parsed.ai_usage,\n cost: parsed.cost,\n extraction_metadata: parsed.extraction_metadata,\n };\n }\n } catch {\n continue;\n }\n }\n }\n } catch (e: any) {\n yield { type: \"error\", error: e.message || \"Stream failed\" };\n }\n }\n\n /**\n * Create an error generator for streaming errors\n */\n private async *createErrorGenerator(\n error: string\n ): AsyncGenerator<AnswerStreamChunk, void, unknown> {\n yield { type: \"error\", error };\n }\n\n /**\n * Datasources: List all available datasources\n * @param options - Optional filter options\n * @param options.category - Filter by category (e.g., \"research\", \"markets\", \"healthcare\")\n * @returns Promise resolving to list of datasources with their metadata\n */\n private async _datasourcesList(\n options: DatasourcesListOptions = {}\n ): Promise<DatasourcesListResponse> {\n try {\n // Build query params\n const params = new URLSearchParams();\n if (options.category) {\n params.append(\"category\", options.category);\n }\n\n const url = `${this.baseUrl}/datasources${\n params.toString() ? `?${params.toString()}` : \"\"\n }`;\n const response = await axios.get(url, { headers: this.headers });\n\n return { success: true, datasources: response.data.datasources };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n\n /**\n * Datasources: Get all available categories\n * @returns Promise resolving to list of categories with their metadata\n */\n private async _datasourcesCategories(): Promise<DatasourcesCategoriesResponse> {\n try {\n const response = await axios.get(`${this.baseUrl}/datasources/categories`, {\n headers: this.headers,\n });\n\n return { success: true, categories: response.data.categories };\n } catch (e: any) {\n return {\n success: false,\n error: e.response?.data?.error || e.message,\n };\n }\n }\n}\n\nexport type {\n SearchResponse,\n SearchType,\n SearchResult,\n FeedbackSentiment,\n FeedbackResponse,\n SearchOptions,\n CountryCode,\n ResponseLength,\n ContentsOptions,\n ContentsResponse,\n ContentResult,\n ExtractEffort,\n ContentResponseLength,\n AnswerOptions,\n AnswerResponse,\n AnswerSuccessResponse,\n AnswerErrorResponse,\n AnswerStreamChunk,\n AnswerStreamChunkType,\n SearchMetadata,\n AIUsage,\n Cost,\n ExtractionMetadata,\n DeepResearchMode,\n DeepResearchStatus,\n DeepResearchOutputFormat,\n ImageType,\n ChartType,\n FileAttachment,\n MCPServerConfig,\n DeepResearchSearchConfig,\n DeepResearchCreateOptions,\n Progress,\n ChartDataPoint,\n ChartDataSeries,\n ImageMetadata,\n DeepResearchSource,\n DeepResearchUsage,\n DeepResearchCreateResponse,\n DeepResearchStatusResponse,\n DeepResearchTaskListItem,\n DeepResearchListResponse,\n DeepResearchUpdateResponse,\n DeepResearchCancelResponse,\n DeepResearchDeleteResponse,\n DeepResearchTogglePublicResponse,\n DeepResearchGetAssetsOptions,\n DeepResearchGetAssetsResponse,\n WaitOptions,\n StreamCallback,\n ListOptions,\n BatchStatus,\n BatchCounts,\n DeepResearchBatch,\n CreateBatchOptions,\n BatchTaskInput,\n AddBatchTasksOptions,\n CreateBatchResponse,\n BatchStatusResponse,\n AddBatchTasksResponse,\n BatchTaskCreated,\n BatchTaskListItem,\n BatchPagination,\n ListBatchTasksOptions,\n ListBatchTasksResponse,\n CancelBatchResponse,\n ListBatchesOptions,\n ListBatchesResponse,\n BatchWaitOptions,\n DatasourceCategoryId,\n DatasourceModality,\n DatasourcePricing,\n DatasourceCoverage,\n Datasource,\n DatasourceCategory,\n DatasourcesListOptions,\n DatasourcesListResponse,\n DatasourcesCategoriesResponse,\n} from \"./types\";\n"],"mappings":";AAAA,OAAO,WAAW;AA2CX,IAAM,QAAN,MAAY;AAAA,EA2DjB,YAAY,QAAiB,UAAkB,2BAA2B;AACxE,QAAI,CAAC,QAAQ;AACX,eAAS,QAAQ,IAAI;AACrB,UAAI,CAAC,QAAQ;AACX,cAAM,IAAI,MAAM,0BAA0B;AAAA,MAC5C;AAAA,IACF;AACA,SAAK,UAAU;AACf,SAAK,UAAU;AAAA,MACb,gBAAgB;AAAA,MAChB,aAAa;AAAA,IACf;AAGA,SAAK,eAAe;AAAA,MAClB,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,MAAM,KAAK,kBAAkB,KAAK,IAAI;AAAA,MACtC,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAoB,KAAK,IAAI;AAAA,MAC1C,QAAQ,KAAK,oBAAo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;AACf,YAAM,EAAE,MAAM,SAAS,OAAO,EAAE,WAAW,gBAAgB;AAAA,IAC7D;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,OAAe,qBACb,OACkD;AAClD,UAAM,EAAE,MAAM,SAAS,MAAM;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAc,iBACZ,UAAkC,CAAC,GACD;AAClC,QAAI;AAEF,YAAM,SAAS,IAAI,gBAAgB;AACnC,UAAI,QAAQ,UAAU;AACpB,eAAO,OAAO,YAAY,QAAQ,QAAQ;AAAA,MAC5C;AAEA,YAAM,MAAM,GAAG,KAAK,OAAO,eACzB,OAAO,SAAS,IAAI,IAAI,OAAO,SAAS,CAAC,KAAK,EAChD;AACA,YAAM,WAAW,MAAM,MAAM,IAAI,KAAK,EAAE,SAAS,KAAK,QAAQ,CAAC;AAE/D,aAAO,EAAE,SAAS,MAAM,aAAa,SAAS,KAAK,YAAY;AAAA,IACjE,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,yBAAiE;AAC7E,QAAI;AACF,YAAM,WAAW,MAAM,MAAM,IAAI,GAAG,KAAK,OAAO,2BAA2B;AAAA,QACzE,SAAS,KAAK;AAAA,MAChB,CAAC;AAED,aAAO,EAAE,SAAS,MAAM,YAAY,SAAS,KAAK,WAAW;AAAA,IAC/D,SAAS,GAAQ;AACf,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO,EAAE,UAAU,MAAM,SAAS,EAAE;AAAA,MACtC;AAAA,IACF;AAAA,EACF;AACF;","names":["response"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "valyu-js",
3
- "version": "2.5.3",
3
+ "version": "2.5.4",
4
4
  "description": "Deepsearch API for AI.",
5
5
  "files": [
6
6
  "dist"