valyu-js 2.3.2 → 2.4.0

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/dist/index.js CHANGED
@@ -58,6 +58,15 @@ var Valyu = class {
58
58
  delete: this._deepresearchDelete.bind(this),
59
59
  togglePublic: this._deepresearchTogglePublic.bind(this)
60
60
  };
61
+ this.batch = {
62
+ create: this._batchCreate.bind(this),
63
+ status: this._batchStatus.bind(this),
64
+ addTasks: this._batchAddTasks.bind(this),
65
+ listTasks: this._batchListTasks.bind(this),
66
+ cancel: this._batchCancel.bind(this),
67
+ list: this._batchList.bind(this),
68
+ waitForCompletion: this._batchWaitForCompletion.bind(this)
69
+ };
61
70
  }
62
71
  /**
63
72
  * Validates date format (YYYY-MM-DD)
@@ -350,9 +359,10 @@ var Valyu = class {
350
359
  * @param urls - Array of URLs to process (max 10)
351
360
  * @param options - Content extraction configuration options
352
361
  * @param options.summary - AI summary configuration: false (raw), true (auto), string (custom), or JSON schema
353
- * @param options.extractEffort - Extraction thoroughness: "normal" or "high"
362
+ * @param options.extractEffort - Extraction thoroughness: "normal", "high", or "auto"
354
363
  * @param options.responseLength - Content length per URL
355
364
  * @param options.maxPriceDollars - Maximum cost limit in USD
365
+ * @param options.screenshot - Request page screenshots (default: false)
356
366
  * @returns Promise resolving to content extraction results
357
367
  */
358
368
  async contents(urls, options = {}) {
@@ -447,6 +457,9 @@ var Valyu = class {
447
457
  if (options.maxPriceDollars !== void 0) {
448
458
  payload.max_price_dollars = options.maxPriceDollars;
449
459
  }
460
+ if (options.screenshot !== void 0) {
461
+ payload.screenshot = options.screenshot;
462
+ }
450
463
  const response = await import_axios.default.post(`${this.baseUrl}/contents`, payload, {
451
464
  headers: this.headers
452
465
  });
@@ -489,7 +502,7 @@ var Valyu = class {
489
502
  }
490
503
  const payload = {
491
504
  input: options.input,
492
- model: options.model || "lite",
505
+ model: options.model || "fast",
493
506
  output_formats: options.outputFormats || ["markdown"],
494
507
  code_execution: options.codeExecution !== false
495
508
  };
@@ -708,6 +721,184 @@ var Valyu = class {
708
721
  };
709
722
  }
710
723
  }
724
+ /**
725
+ * Batch: Create a new batch
726
+ * @param options - Batch configuration options
727
+ * @param options.name - Optional name for the batch
728
+ * @param options.model - DeepResearch mode: "fast", "standard", or "heavy" (default: "standard")
729
+ * @param options.outputFormats - Output formats for tasks (default: ["markdown"])
730
+ * @param options.search - Search configuration for all tasks in batch
731
+ * @param options.webhookUrl - Optional HTTPS URL for completion notification
732
+ * @param options.metadata - Optional metadata key-value pairs
733
+ * @returns Promise resolving to batch creation response with batch_id and webhook_secret
734
+ */
735
+ async _batchCreate(options = {}) {
736
+ try {
737
+ const payload = {};
738
+ if (options.name) payload.name = options.name;
739
+ if (options.model) payload.model = options.model;
740
+ if (options.outputFormats) payload.output_formats = options.outputFormats;
741
+ if (options.search) {
742
+ payload.search = {
743
+ search_type: options.search.searchType,
744
+ included_sources: options.search.includedSources
745
+ };
746
+ }
747
+ if (options.webhookUrl) payload.webhook_url = options.webhookUrl;
748
+ if (options.metadata) payload.metadata = options.metadata;
749
+ const response = await import_axios.default.post(
750
+ `${this.baseUrl}/deepresearch/batches`,
751
+ payload,
752
+ { headers: this.headers }
753
+ );
754
+ return { success: true, ...response.data };
755
+ } catch (e) {
756
+ return {
757
+ success: false,
758
+ error: e.response?.data?.error || e.message
759
+ };
760
+ }
761
+ }
762
+ /**
763
+ * Batch: Get batch status
764
+ * @param batchId - The batch ID to query
765
+ * @returns Promise resolving to batch status with counts and usage
766
+ */
767
+ async _batchStatus(batchId) {
768
+ try {
769
+ const response = await import_axios.default.get(
770
+ `${this.baseUrl}/deepresearch/batches/${batchId}`,
771
+ { headers: this.headers }
772
+ );
773
+ return { success: true, batch: response.data };
774
+ } catch (e) {
775
+ return {
776
+ success: false,
777
+ error: e.response?.data?.error || e.message
778
+ };
779
+ }
780
+ }
781
+ /**
782
+ * Batch: Add tasks to a batch
783
+ * @param batchId - The batch ID to add tasks to
784
+ * @param options - Task configuration options
785
+ * @param options.tasks - Array of task inputs
786
+ * @returns Promise resolving to response with added_count and task_ids
787
+ */
788
+ async _batchAddTasks(batchId, options) {
789
+ try {
790
+ if (!options.tasks || !Array.isArray(options.tasks)) {
791
+ return {
792
+ success: false,
793
+ error: "tasks must be an array"
794
+ };
795
+ }
796
+ if (options.tasks.length === 0) {
797
+ return {
798
+ success: false,
799
+ error: "tasks array cannot be empty"
800
+ };
801
+ }
802
+ const response = await import_axios.default.post(
803
+ `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,
804
+ { tasks: options.tasks },
805
+ { headers: this.headers }
806
+ );
807
+ return { success: true, ...response.data };
808
+ } catch (e) {
809
+ return {
810
+ success: false,
811
+ error: e.response?.data?.error || e.message
812
+ };
813
+ }
814
+ }
815
+ /**
816
+ * Batch: List all tasks in a batch
817
+ * @param batchId - The batch ID to query
818
+ * @returns Promise resolving to list of tasks with their status
819
+ */
820
+ async _batchListTasks(batchId) {
821
+ try {
822
+ const response = await import_axios.default.get(
823
+ `${this.baseUrl}/deepresearch/batches/${batchId}/tasks`,
824
+ { headers: this.headers }
825
+ );
826
+ return { success: true, ...response.data };
827
+ } catch (e) {
828
+ return {
829
+ success: false,
830
+ error: e.response?.data?.error || e.message
831
+ };
832
+ }
833
+ }
834
+ /**
835
+ * Batch: Cancel a batch and all its pending tasks
836
+ * @param batchId - The batch ID to cancel
837
+ * @returns Promise resolving to cancellation confirmation
838
+ */
839
+ async _batchCancel(batchId) {
840
+ try {
841
+ const response = await import_axios.default.post(
842
+ `${this.baseUrl}/deepresearch/batches/${batchId}/cancel`,
843
+ {},
844
+ { headers: this.headers }
845
+ );
846
+ return { success: true, ...response.data };
847
+ } catch (e) {
848
+ return {
849
+ success: false,
850
+ error: e.response?.data?.error || e.message
851
+ };
852
+ }
853
+ }
854
+ /**
855
+ * Batch: List all batches
856
+ * @returns Promise resolving to list of all batches
857
+ */
858
+ async _batchList() {
859
+ try {
860
+ const response = await import_axios.default.get(`${this.baseUrl}/deepresearch/batches`, {
861
+ headers: this.headers
862
+ });
863
+ return { success: true, batches: response.data };
864
+ } catch (e) {
865
+ return {
866
+ success: false,
867
+ error: e.response?.data?.error || e.message
868
+ };
869
+ }
870
+ }
871
+ /**
872
+ * Batch: Wait for batch completion with polling
873
+ * @param batchId - The batch ID to wait for
874
+ * @param options - Wait configuration options
875
+ * @param options.pollInterval - Polling interval in milliseconds (default: 10000)
876
+ * @param options.maxWaitTime - Maximum wait time in milliseconds (default: 7200000)
877
+ * @param options.onProgress - Callback for progress updates
878
+ * @returns Promise resolving to final batch status
879
+ */
880
+ async _batchWaitForCompletion(batchId, options = {}) {
881
+ const pollInterval = options.pollInterval || 1e4;
882
+ const maxWaitTime = options.maxWaitTime || 72e5;
883
+ const startTime = Date.now();
884
+ while (true) {
885
+ const statusResponse = await this._batchStatus(batchId);
886
+ if (!statusResponse.success || !statusResponse.batch) {
887
+ throw new Error(statusResponse.error || "Failed to get batch status");
888
+ }
889
+ const batch = statusResponse.batch;
890
+ if (options.onProgress) {
891
+ options.onProgress(batch);
892
+ }
893
+ if (batch.status === "completed" || batch.status === "completed_with_errors" || batch.status === "cancelled") {
894
+ return batch;
895
+ }
896
+ if (Date.now() - startTime > maxWaitTime) {
897
+ throw new Error("Maximum wait time exceeded");
898
+ }
899
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
900
+ }
901
+ }
711
902
  /**
712
903
  * Get AI-powered answers using the Valyu Answer API
713
904
  * @param query - The question or query string
@@ -787,7 +978,9 @@ var Valyu = class {
787
978
  }
788
979
  const validation = this.validateSources(options.includedSources);
789
980
  if (!validation.valid) {
790
- return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(", ")}.`;
981
+ return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(
982
+ ", "
983
+ )}.`;
791
984
  }
792
985
  }
793
986
  if (options.excludedSources !== void 0) {
@@ -796,7 +989,9 @@ var Valyu = class {
796
989
  }
797
990
  const validation = this.validateSources(options.excludedSources);
798
991
  if (!validation.valid) {
799
- return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(", ")}.`;
992
+ return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(
993
+ ", "
994
+ )}.`;
800
995
  }
801
996
  }
802
997
  return null;
@@ -815,12 +1010,18 @@ var Valyu = class {
815
1010
  query: query.trim(),
816
1011
  search_type: finalSearchType
817
1012
  };
818
- if (options.dataMaxPrice !== void 0) payload.data_max_price = options.dataMaxPrice;
819
- if (options.structuredOutput !== void 0) payload.structured_output = options.structuredOutput;
820
- if (options.systemInstructions !== void 0) payload.system_instructions = options.systemInstructions.trim();
821
- if (options.countryCode !== void 0) payload.country_code = options.countryCode;
822
- if (options.includedSources !== void 0) payload.included_sources = options.includedSources;
823
- if (options.excludedSources !== void 0) payload.excluded_sources = options.excludedSources;
1013
+ if (options.dataMaxPrice !== void 0)
1014
+ payload.data_max_price = options.dataMaxPrice;
1015
+ if (options.structuredOutput !== void 0)
1016
+ payload.structured_output = options.structuredOutput;
1017
+ if (options.systemInstructions !== void 0)
1018
+ payload.system_instructions = options.systemInstructions.trim();
1019
+ if (options.countryCode !== void 0)
1020
+ payload.country_code = options.countryCode;
1021
+ if (options.includedSources !== void 0)
1022
+ payload.included_sources = options.includedSources;
1023
+ if (options.excludedSources !== void 0)
1024
+ payload.excluded_sources = options.excludedSources;
824
1025
  if (options.startDate !== void 0) payload.start_date = options.startDate;
825
1026
  if (options.endDate !== void 0) payload.end_date = options.endDate;
826
1027
  if (options.fastMode !== void 0) payload.fast_mode = options.fastMode;
@@ -835,7 +1036,7 @@ var Valyu = class {
835
1036
  method: "POST",
836
1037
  headers: {
837
1038
  ...this.headers,
838
- "Accept": "text/event-stream"
1039
+ Accept: "text/event-stream"
839
1040
  },
840
1041
  body: JSON.stringify(payload)
841
1042
  });
@@ -888,9 +1089,20 @@ var Valyu = class {
888
1089
  contents: fullContent || finalMetadata.contents || "",
889
1090
  data_type: finalMetadata.data_type || "unstructured",
890
1091
  search_results: finalSearchResults,
891
- search_metadata: finalMetadata.search_metadata || { tx_ids: [], number_of_results: 0, total_characters: 0 },
892
- ai_usage: finalMetadata.ai_usage || { input_tokens: 0, output_tokens: 0 },
893
- cost: finalMetadata.cost || { total_deduction_dollars: 0, search_deduction_dollars: 0, ai_deduction_dollars: 0 }
1092
+ search_metadata: finalMetadata.search_metadata || {
1093
+ tx_ids: [],
1094
+ number_of_results: 0,
1095
+ total_characters: 0
1096
+ },
1097
+ ai_usage: finalMetadata.ai_usage || {
1098
+ input_tokens: 0,
1099
+ output_tokens: 0
1100
+ },
1101
+ cost: finalMetadata.cost || {
1102
+ total_deduction_dollars: 0,
1103
+ search_deduction_dollars: 0,
1104
+ ai_deduction_dollars: 0
1105
+ }
894
1106
  };
895
1107
  if (finalMetadata.extraction_metadata) {
896
1108
  response2.extraction_metadata = finalMetadata.extraction_metadata;
@@ -917,13 +1129,16 @@ var Valyu = class {
917
1129
  method: "POST",
918
1130
  headers: {
919
1131
  ...this.headers,
920
- "Accept": "text/event-stream"
1132
+ Accept: "text/event-stream"
921
1133
  },
922
1134
  body: JSON.stringify(payload)
923
1135
  });
924
1136
  if (!response.ok) {
925
1137
  const errorData = await response.json().catch(() => ({}));
926
- yield { type: "error", error: errorData.error || `HTTP Error: ${response.status}` };
1138
+ yield {
1139
+ type: "error",
1140
+ error: errorData.error || `HTTP Error: ${response.status}`
1141
+ };
927
1142
  return;
928
1143
  }
929
1144
  const reader = response.body?.getReader();
@@ -949,7 +1164,10 @@ var Valyu = class {
949
1164
  try {
950
1165
  const parsed = JSON.parse(dataStr);
951
1166
  if (parsed.search_results && parsed.success === void 0) {
952
- yield { type: "search_results", search_results: parsed.search_results };
1167
+ yield {
1168
+ type: "search_results",
1169
+ search_results: parsed.search_results
1170
+ };
953
1171
  } else if (parsed.choices) {
954
1172
  const delta = parsed.choices[0]?.delta || {};
955
1173
  const content = delta.content || "";