valyu-js 2.2.0 → 2.2.1

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.d.mts CHANGED
@@ -6,14 +6,14 @@ type ResponseLength = "short" | "medium" | "large" | "max" | number;
6
6
  interface SearchResult {
7
7
  title: string;
8
8
  url: string;
9
- content: string;
9
+ content: string | object | any[];
10
10
  description?: string;
11
11
  source: string;
12
- price: number;
12
+ source_type?: string;
13
+ data_type?: DataType;
14
+ date?: string;
13
15
  length: number;
14
16
  relevance_score?: number;
15
- data_type?: DataType;
16
- source_type?: string;
17
17
  publication_date?: string;
18
18
  id?: string;
19
19
  image_url?: Record<string, string>;
@@ -95,6 +95,7 @@ interface AnswerOptions {
95
95
  startDate?: string;
96
96
  endDate?: string;
97
97
  fastMode?: boolean;
98
+ streaming?: boolean;
98
99
  }
99
100
  interface SearchMetadata {
100
101
  tx_ids: string[];
@@ -109,6 +110,7 @@ interface Cost {
109
110
  total_deduction_dollars: number;
110
111
  search_deduction_dollars: number;
111
112
  ai_deduction_dollars: number;
113
+ contents_deduction_dollars?: number;
112
114
  }
113
115
  interface AnswerSuccessResponse {
114
116
  success: true;
@@ -126,9 +128,24 @@ interface AnswerErrorResponse {
126
128
  error: string;
127
129
  }
128
130
  type AnswerResponse = AnswerSuccessResponse | AnswerErrorResponse;
131
+ type AnswerStreamChunkType = "search_results" | "content" | "metadata" | "done" | "error";
132
+ interface AnswerStreamChunk {
133
+ type: AnswerStreamChunkType;
134
+ search_results?: SearchResult[];
135
+ content?: string;
136
+ finish_reason?: string;
137
+ ai_tx_id?: string;
138
+ original_query?: string;
139
+ data_type?: "structured" | "unstructured";
140
+ search_metadata?: SearchMetadata;
141
+ ai_usage?: AIUsage;
142
+ cost?: Cost;
143
+ error?: string;
144
+ }
129
145
  type DeepResearchMode = "lite" | "heavy";
130
146
  type DeepResearchStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
131
- type DeepResearchOutputFormat = "markdown" | "pdf";
147
+ type DeepResearchOutputFormat = "markdown" | "pdf" | Record<string, any>;
148
+ type DeepResearchOutputType = "markdown" | "json";
132
149
  type ImageType = "chart" | "ai_generated";
133
150
  type ChartType = "line" | "bar" | "area";
134
151
  interface FileAttachment {
@@ -238,7 +255,8 @@ interface DeepResearchStatusResponse {
238
255
  progress?: Progress;
239
256
  messages?: any[];
240
257
  completed_at?: number;
241
- output?: string;
258
+ output?: string | Record<string, any>;
259
+ output_type?: DeepResearchOutputType;
242
260
  pdf_url?: string;
243
261
  images?: ImageMetadata[];
244
262
  sources?: DeepResearchSource[];
@@ -419,9 +437,30 @@ declare class Valyu {
419
437
  * @param options.startDate - Start date filter (YYYY-MM-DD format)
420
438
  * @param options.endDate - End date filter (YYYY-MM-DD format)
421
439
  * @param options.fastMode - Fast mode for quicker but shorter results (default: false)
422
- * @returns Promise resolving to answer response
440
+ * @param options.streaming - Enable streaming mode (default: false)
441
+ * @returns Promise resolving to answer response, or AsyncGenerator for streaming
442
+ */
443
+ answer(query: string, options?: AnswerOptions): Promise<AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>>;
444
+ /**
445
+ * Validate answer parameters
446
+ */
447
+ private validateAnswerParams;
448
+ /**
449
+ * Build payload for answer API
450
+ */
451
+ private buildAnswerPayload;
452
+ /**
453
+ * Fetch answer (non-streaming mode)
454
+ */
455
+ private fetchAnswer;
456
+ /**
457
+ * Stream answer using SSE
458
+ */
459
+ private streamAnswer;
460
+ /**
461
+ * Create an error generator for streaming errors
423
462
  */
424
- answer(query: string, options?: AnswerOptions): Promise<AnswerResponse>;
463
+ private createErrorGenerator;
425
464
  }
426
465
 
427
- export { type AIUsage, type AnswerErrorResponse, type AnswerOptions, type AnswerResponse, type AnswerSuccessResponse, type ChartDataPoint, type ChartDataSeries, type ChartType, type ContentResponseLength, type ContentResult, type ContentsOptions, type ContentsResponse, type Cost, type CountryCode, type DeepResearchCancelResponse, type DeepResearchCreateOptions, type DeepResearchCreateResponse, type DeepResearchDeleteResponse, type DeepResearchListResponse, type DeepResearchMode, type DeepResearchOutputFormat, type DeepResearchSearchConfig, type DeepResearchSource, type DeepResearchStatus, type DeepResearchStatusResponse, type DeepResearchTaskListItem, type DeepResearchTogglePublicResponse, type DeepResearchUpdateResponse, type DeepResearchUsage, type ExtractEffort, type FeedbackResponse, type FeedbackSentiment, type FileAttachment, type ImageMetadata, type ImageType, type ListOptions, type MCPServerConfig, type Progress, type ResponseLength, type SearchMetadata, type SearchOptions, type SearchResponse, type SearchType, type StreamCallback, Valyu, type WaitOptions };
466
+ export { type AIUsage, type AnswerErrorResponse, type AnswerOptions, type AnswerResponse, type AnswerStreamChunk, type AnswerStreamChunkType, type AnswerSuccessResponse, type ChartDataPoint, type ChartDataSeries, type ChartType, type ContentResponseLength, type ContentResult, type ContentsOptions, type ContentsResponse, type Cost, type CountryCode, type DeepResearchCancelResponse, type DeepResearchCreateOptions, type DeepResearchCreateResponse, type DeepResearchDeleteResponse, type DeepResearchListResponse, type DeepResearchMode, type DeepResearchOutputFormat, type DeepResearchSearchConfig, type DeepResearchSource, type DeepResearchStatus, type DeepResearchStatusResponse, type DeepResearchTaskListItem, type DeepResearchTogglePublicResponse, type DeepResearchUpdateResponse, type DeepResearchUsage, type ExtractEffort, type FeedbackResponse, type FeedbackSentiment, type FileAttachment, type ImageMetadata, type ImageType, type ListOptions, type MCPServerConfig, type Progress, type ResponseLength, type SearchMetadata, type SearchOptions, type SearchResponse, type SearchResult, type SearchType, type StreamCallback, Valyu, type WaitOptions };
package/dist/index.d.ts CHANGED
@@ -6,14 +6,14 @@ type ResponseLength = "short" | "medium" | "large" | "max" | number;
6
6
  interface SearchResult {
7
7
  title: string;
8
8
  url: string;
9
- content: string;
9
+ content: string | object | any[];
10
10
  description?: string;
11
11
  source: string;
12
- price: number;
12
+ source_type?: string;
13
+ data_type?: DataType;
14
+ date?: string;
13
15
  length: number;
14
16
  relevance_score?: number;
15
- data_type?: DataType;
16
- source_type?: string;
17
17
  publication_date?: string;
18
18
  id?: string;
19
19
  image_url?: Record<string, string>;
@@ -95,6 +95,7 @@ interface AnswerOptions {
95
95
  startDate?: string;
96
96
  endDate?: string;
97
97
  fastMode?: boolean;
98
+ streaming?: boolean;
98
99
  }
99
100
  interface SearchMetadata {
100
101
  tx_ids: string[];
@@ -109,6 +110,7 @@ interface Cost {
109
110
  total_deduction_dollars: number;
110
111
  search_deduction_dollars: number;
111
112
  ai_deduction_dollars: number;
113
+ contents_deduction_dollars?: number;
112
114
  }
113
115
  interface AnswerSuccessResponse {
114
116
  success: true;
@@ -126,9 +128,24 @@ interface AnswerErrorResponse {
126
128
  error: string;
127
129
  }
128
130
  type AnswerResponse = AnswerSuccessResponse | AnswerErrorResponse;
131
+ type AnswerStreamChunkType = "search_results" | "content" | "metadata" | "done" | "error";
132
+ interface AnswerStreamChunk {
133
+ type: AnswerStreamChunkType;
134
+ search_results?: SearchResult[];
135
+ content?: string;
136
+ finish_reason?: string;
137
+ ai_tx_id?: string;
138
+ original_query?: string;
139
+ data_type?: "structured" | "unstructured";
140
+ search_metadata?: SearchMetadata;
141
+ ai_usage?: AIUsage;
142
+ cost?: Cost;
143
+ error?: string;
144
+ }
129
145
  type DeepResearchMode = "lite" | "heavy";
130
146
  type DeepResearchStatus = "queued" | "running" | "completed" | "failed" | "cancelled";
131
- type DeepResearchOutputFormat = "markdown" | "pdf";
147
+ type DeepResearchOutputFormat = "markdown" | "pdf" | Record<string, any>;
148
+ type DeepResearchOutputType = "markdown" | "json";
132
149
  type ImageType = "chart" | "ai_generated";
133
150
  type ChartType = "line" | "bar" | "area";
134
151
  interface FileAttachment {
@@ -238,7 +255,8 @@ interface DeepResearchStatusResponse {
238
255
  progress?: Progress;
239
256
  messages?: any[];
240
257
  completed_at?: number;
241
- output?: string;
258
+ output?: string | Record<string, any>;
259
+ output_type?: DeepResearchOutputType;
242
260
  pdf_url?: string;
243
261
  images?: ImageMetadata[];
244
262
  sources?: DeepResearchSource[];
@@ -419,9 +437,30 @@ declare class Valyu {
419
437
  * @param options.startDate - Start date filter (YYYY-MM-DD format)
420
438
  * @param options.endDate - End date filter (YYYY-MM-DD format)
421
439
  * @param options.fastMode - Fast mode for quicker but shorter results (default: false)
422
- * @returns Promise resolving to answer response
440
+ * @param options.streaming - Enable streaming mode (default: false)
441
+ * @returns Promise resolving to answer response, or AsyncGenerator for streaming
442
+ */
443
+ answer(query: string, options?: AnswerOptions): Promise<AnswerResponse | AsyncGenerator<AnswerStreamChunk, void, unknown>>;
444
+ /**
445
+ * Validate answer parameters
446
+ */
447
+ private validateAnswerParams;
448
+ /**
449
+ * Build payload for answer API
450
+ */
451
+ private buildAnswerPayload;
452
+ /**
453
+ * Fetch answer (non-streaming mode)
454
+ */
455
+ private fetchAnswer;
456
+ /**
457
+ * Stream answer using SSE
458
+ */
459
+ private streamAnswer;
460
+ /**
461
+ * Create an error generator for streaming errors
423
462
  */
424
- answer(query: string, options?: AnswerOptions): Promise<AnswerResponse>;
463
+ private createErrorGenerator;
425
464
  }
426
465
 
427
- export { type AIUsage, type AnswerErrorResponse, type AnswerOptions, type AnswerResponse, type AnswerSuccessResponse, type ChartDataPoint, type ChartDataSeries, type ChartType, type ContentResponseLength, type ContentResult, type ContentsOptions, type ContentsResponse, type Cost, type CountryCode, type DeepResearchCancelResponse, type DeepResearchCreateOptions, type DeepResearchCreateResponse, type DeepResearchDeleteResponse, type DeepResearchListResponse, type DeepResearchMode, type DeepResearchOutputFormat, type DeepResearchSearchConfig, type DeepResearchSource, type DeepResearchStatus, type DeepResearchStatusResponse, type DeepResearchTaskListItem, type DeepResearchTogglePublicResponse, type DeepResearchUpdateResponse, type DeepResearchUsage, type ExtractEffort, type FeedbackResponse, type FeedbackSentiment, type FileAttachment, type ImageMetadata, type ImageType, type ListOptions, type MCPServerConfig, type Progress, type ResponseLength, type SearchMetadata, type SearchOptions, type SearchResponse, type SearchType, type StreamCallback, Valyu, type WaitOptions };
466
+ export { type AIUsage, type AnswerErrorResponse, type AnswerOptions, type AnswerResponse, type AnswerStreamChunk, type AnswerStreamChunkType, type AnswerSuccessResponse, type ChartDataPoint, type ChartDataSeries, type ChartType, type ContentResponseLength, type ContentResult, type ContentsOptions, type ContentsResponse, type Cost, type CountryCode, type DeepResearchCancelResponse, type DeepResearchCreateOptions, type DeepResearchCreateResponse, type DeepResearchDeleteResponse, type DeepResearchListResponse, type DeepResearchMode, type DeepResearchOutputFormat, type DeepResearchSearchConfig, type DeepResearchSource, type DeepResearchStatus, type DeepResearchStatusResponse, type DeepResearchTaskListItem, type DeepResearchTogglePublicResponse, type DeepResearchUpdateResponse, type DeepResearchUsage, type ExtractEffort, type FeedbackResponse, type FeedbackSentiment, type FileAttachment, type ImageMetadata, type ImageType, type ListOptions, type MCPServerConfig, type Progress, type ResponseLength, type SearchMetadata, type SearchOptions, type SearchResponse, type SearchResult, type SearchType, type StreamCallback, Valyu, type WaitOptions };
package/dist/index.js CHANGED
@@ -721,164 +721,264 @@ var Valyu = class {
721
721
  * @param options.startDate - Start date filter (YYYY-MM-DD format)
722
722
  * @param options.endDate - End date filter (YYYY-MM-DD format)
723
723
  * @param options.fastMode - Fast mode for quicker but shorter results (default: false)
724
- * @returns Promise resolving to answer response
724
+ * @param options.streaming - Enable streaming mode (default: false)
725
+ * @returns Promise resolving to answer response, or AsyncGenerator for streaming
725
726
  */
726
727
  async answer(query, options = {}) {
727
- try {
728
- const defaultSearchType = "all";
729
- if (!query || typeof query !== "string" || query.trim().length === 0) {
730
- return {
731
- success: false,
732
- error: "Query is required and must be a non-empty string"
733
- };
734
- }
735
- let finalSearchType = defaultSearchType;
736
- const providedSearchTypeString = options.searchType?.toLowerCase();
737
- if (providedSearchTypeString === "web" || providedSearchTypeString === "proprietary" || providedSearchTypeString === "all" || providedSearchTypeString === "news") {
738
- finalSearchType = providedSearchTypeString;
739
- } else if (options.searchType !== void 0) {
740
- return {
741
- success: false,
742
- error: "Invalid searchType provided. Must be one of: all, web, proprietary, news"
743
- };
728
+ const validationError = this.validateAnswerParams(query, options);
729
+ if (validationError) {
730
+ if (options.streaming) {
731
+ return this.createErrorGenerator(validationError);
744
732
  }
745
- if (options.systemInstructions !== void 0) {
746
- if (typeof options.systemInstructions !== "string") {
747
- return {
748
- success: false,
749
- error: "systemInstructions must be a string"
750
- };
751
- }
752
- const trimmed = options.systemInstructions.trim();
753
- if (trimmed.length === 0) {
754
- return {
755
- success: false,
756
- error: "systemInstructions cannot be empty when provided"
757
- };
758
- }
759
- if (trimmed.length > 2e3) {
760
- return {
761
- success: false,
762
- error: "systemInstructions must be 2000 characters or less"
763
- };
764
- }
765
- }
766
- if (options.dataMaxPrice !== void 0) {
767
- if (typeof options.dataMaxPrice !== "number" || options.dataMaxPrice <= 0) {
768
- return {
769
- success: false,
770
- error: "dataMaxPrice must be a positive number"
771
- };
772
- }
773
- }
774
- if (options.startDate && !this.validateDateFormat(options.startDate)) {
775
- return {
776
- success: false,
777
- error: "Invalid startDate format. Must be YYYY-MM-DD"
778
- };
779
- }
780
- if (options.endDate && !this.validateDateFormat(options.endDate)) {
781
- return {
782
- success: false,
783
- error: "Invalid endDate format. Must be YYYY-MM-DD"
784
- };
785
- }
786
- if (options.startDate && options.endDate) {
787
- const startDate = new Date(options.startDate);
788
- const endDate = new Date(options.endDate);
789
- if (startDate > endDate) {
790
- return {
791
- success: false,
792
- error: "startDate must be before endDate"
793
- };
794
- }
795
- }
796
- if (options.includedSources !== void 0) {
797
- if (!Array.isArray(options.includedSources)) {
798
- return {
799
- success: false,
800
- error: "includedSources must be an array"
801
- };
802
- }
803
- const includedSourcesValidation = this.validateSources(
804
- options.includedSources
805
- );
806
- if (!includedSourcesValidation.valid) {
807
- return {
808
- success: false,
809
- error: `Invalid includedSources format. Invalid sources: ${includedSourcesValidation.invalidSources.join(
810
- ", "
811
- )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`
812
- };
813
- }
814
- }
815
- if (options.excludedSources !== void 0) {
816
- if (!Array.isArray(options.excludedSources)) {
817
- return {
818
- success: false,
819
- error: "excludedSources must be an array"
820
- };
821
- }
822
- const excludedSourcesValidation = this.validateSources(
823
- options.excludedSources
824
- );
825
- if (!excludedSourcesValidation.valid) {
826
- return {
827
- success: false,
828
- error: `Invalid excludedSources format. Invalid sources: ${excludedSourcesValidation.invalidSources.join(
829
- ", "
830
- )}. Sources must be valid URLs, domains (with optional paths), or dataset identifiers in 'provider/dataset' format.`
831
- };
832
- }
833
- }
834
- const payload = {
835
- query: query.trim(),
836
- search_type: finalSearchType
837
- };
838
- if (options.dataMaxPrice !== void 0) {
839
- payload.data_max_price = options.dataMaxPrice;
733
+ return { success: false, error: validationError };
734
+ }
735
+ const payload = this.buildAnswerPayload(query, options);
736
+ if (options.streaming) {
737
+ return this.streamAnswer(payload);
738
+ } else {
739
+ return this.fetchAnswer(payload);
740
+ }
741
+ }
742
+ /**
743
+ * Validate answer parameters
744
+ */
745
+ validateAnswerParams(query, options) {
746
+ if (!query || typeof query !== "string" || query.trim().length === 0) {
747
+ return "Query is required and must be a non-empty string";
748
+ }
749
+ const providedSearchTypeString = options.searchType?.toLowerCase();
750
+ if (providedSearchTypeString !== void 0 && providedSearchTypeString !== "web" && providedSearchTypeString !== "proprietary" && providedSearchTypeString !== "all" && providedSearchTypeString !== "news") {
751
+ return "Invalid searchType provided. Must be one of: all, web, proprietary, news";
752
+ }
753
+ if (options.systemInstructions !== void 0) {
754
+ if (typeof options.systemInstructions !== "string") {
755
+ return "systemInstructions must be a string";
840
756
  }
841
- if (options.structuredOutput !== void 0) {
842
- payload.structured_output = options.structuredOutput;
757
+ const trimmed = options.systemInstructions.trim();
758
+ if (trimmed.length === 0) {
759
+ return "systemInstructions cannot be empty when provided";
843
760
  }
844
- if (options.systemInstructions !== void 0) {
845
- payload.system_instructions = options.systemInstructions.trim();
761
+ if (trimmed.length > 2e3) {
762
+ return "systemInstructions must be 2000 characters or less";
846
763
  }
847
- if (options.countryCode !== void 0) {
848
- payload.country_code = options.countryCode;
764
+ }
765
+ if (options.dataMaxPrice !== void 0) {
766
+ if (typeof options.dataMaxPrice !== "number" || options.dataMaxPrice <= 0) {
767
+ return "dataMaxPrice must be a positive number";
849
768
  }
850
- if (options.includedSources !== void 0) {
851
- payload.included_sources = options.includedSources;
769
+ }
770
+ if (options.startDate && !this.validateDateFormat(options.startDate)) {
771
+ return "Invalid startDate format. Must be YYYY-MM-DD";
772
+ }
773
+ if (options.endDate && !this.validateDateFormat(options.endDate)) {
774
+ return "Invalid endDate format. Must be YYYY-MM-DD";
775
+ }
776
+ if (options.startDate && options.endDate) {
777
+ const startDate = new Date(options.startDate);
778
+ const endDate = new Date(options.endDate);
779
+ if (startDate > endDate) {
780
+ return "startDate must be before endDate";
852
781
  }
853
- if (options.excludedSources !== void 0) {
854
- payload.excluded_sources = options.excludedSources;
782
+ }
783
+ if (options.includedSources !== void 0) {
784
+ if (!Array.isArray(options.includedSources)) {
785
+ return "includedSources must be an array";
855
786
  }
856
- if (options.startDate !== void 0) {
857
- payload.start_date = options.startDate;
787
+ const validation = this.validateSources(options.includedSources);
788
+ if (!validation.valid) {
789
+ return `Invalid includedSources format. Invalid sources: ${validation.invalidSources.join(", ")}.`;
858
790
  }
859
- if (options.endDate !== void 0) {
860
- payload.end_date = options.endDate;
791
+ }
792
+ if (options.excludedSources !== void 0) {
793
+ if (!Array.isArray(options.excludedSources)) {
794
+ return "excludedSources must be an array";
861
795
  }
862
- if (options.fastMode !== void 0) {
863
- payload.fast_mode = options.fastMode;
796
+ const validation = this.validateSources(options.excludedSources);
797
+ if (!validation.valid) {
798
+ return `Invalid excludedSources format. Invalid sources: ${validation.invalidSources.join(", ")}.`;
864
799
  }
865
- const response = await import_axios.default.post(`${this.baseUrl}/answer`, payload, {
866
- headers: this.headers
800
+ }
801
+ return null;
802
+ }
803
+ /**
804
+ * Build payload for answer API
805
+ */
806
+ buildAnswerPayload(query, options) {
807
+ const defaultSearchType = "all";
808
+ const providedSearchTypeString = options.searchType?.toLowerCase();
809
+ let finalSearchType = defaultSearchType;
810
+ if (providedSearchTypeString === "web" || providedSearchTypeString === "proprietary" || providedSearchTypeString === "all" || providedSearchTypeString === "news") {
811
+ finalSearchType = providedSearchTypeString;
812
+ }
813
+ const payload = {
814
+ query: query.trim(),
815
+ search_type: finalSearchType
816
+ };
817
+ if (options.dataMaxPrice !== void 0) payload.data_max_price = options.dataMaxPrice;
818
+ if (options.structuredOutput !== void 0) payload.structured_output = options.structuredOutput;
819
+ if (options.systemInstructions !== void 0) payload.system_instructions = options.systemInstructions.trim();
820
+ if (options.countryCode !== void 0) payload.country_code = options.countryCode;
821
+ if (options.includedSources !== void 0) payload.included_sources = options.includedSources;
822
+ if (options.excludedSources !== void 0) payload.excluded_sources = options.excludedSources;
823
+ if (options.startDate !== void 0) payload.start_date = options.startDate;
824
+ if (options.endDate !== void 0) payload.end_date = options.endDate;
825
+ if (options.fastMode !== void 0) payload.fast_mode = options.fastMode;
826
+ return payload;
827
+ }
828
+ /**
829
+ * Fetch answer (non-streaming mode)
830
+ */
831
+ async fetchAnswer(payload) {
832
+ try {
833
+ const response = await fetch(`${this.baseUrl}/answer`, {
834
+ method: "POST",
835
+ headers: {
836
+ ...this.headers,
837
+ "Accept": "text/event-stream"
838
+ },
839
+ body: JSON.stringify(payload)
867
840
  });
868
- if (!response.status || response.status < 200 || response.status >= 300) {
841
+ if (!response.ok) {
842
+ const errorData = await response.json().catch(() => ({}));
869
843
  return {
870
844
  success: false,
871
- error: response.data?.error || "Request failed"
845
+ error: errorData.error || `HTTP Error: ${response.status}`
872
846
  };
873
847
  }
874
- return response.data;
848
+ let fullContent = "";
849
+ let searchResults = [];
850
+ let finalMetadata = {};
851
+ const reader = response.body?.getReader();
852
+ const decoder = new TextDecoder();
853
+ let buffer = "";
854
+ if (reader) {
855
+ while (true) {
856
+ const { done, value } = await reader.read();
857
+ if (done) break;
858
+ buffer += decoder.decode(value, { stream: true });
859
+ const lines = buffer.split("\n");
860
+ buffer = lines.pop() || "";
861
+ for (const line of lines) {
862
+ if (!line.startsWith("data: ")) continue;
863
+ const dataStr = line.slice(6);
864
+ if (dataStr === "[DONE]") continue;
865
+ try {
866
+ const parsed = JSON.parse(dataStr);
867
+ if (parsed.search_results && !parsed.success) {
868
+ searchResults = [...searchResults, ...parsed.search_results];
869
+ } else if (parsed.choices) {
870
+ const content = parsed.choices[0]?.delta?.content || "";
871
+ if (content) fullContent += content;
872
+ } else if (parsed.success !== void 0) {
873
+ finalMetadata = parsed;
874
+ }
875
+ } catch {
876
+ continue;
877
+ }
878
+ }
879
+ }
880
+ }
881
+ if (finalMetadata.success) {
882
+ const finalSearchResults = finalMetadata.search_results || searchResults;
883
+ return {
884
+ success: true,
885
+ ai_tx_id: finalMetadata.ai_tx_id || "",
886
+ original_query: finalMetadata.original_query || payload.query,
887
+ contents: fullContent || finalMetadata.contents || "",
888
+ data_type: finalMetadata.data_type || "unstructured",
889
+ search_results: finalSearchResults,
890
+ search_metadata: finalMetadata.search_metadata || { tx_ids: [], number_of_results: 0, total_characters: 0 },
891
+ ai_usage: finalMetadata.ai_usage || { input_tokens: 0, output_tokens: 0 },
892
+ cost: finalMetadata.cost || { total_deduction_dollars: 0, search_deduction_dollars: 0, ai_deduction_dollars: 0 }
893
+ };
894
+ }
895
+ return {
896
+ success: false,
897
+ error: finalMetadata.error || "Unknown error occurred"
898
+ };
875
899
  } catch (e) {
876
900
  return {
877
901
  success: false,
878
- error: e.response?.data?.error || e.message
902
+ error: e.message || "Request failed"
879
903
  };
880
904
  }
881
905
  }
906
+ /**
907
+ * Stream answer using SSE
908
+ */
909
+ async *streamAnswer(payload) {
910
+ try {
911
+ const response = await fetch(`${this.baseUrl}/answer`, {
912
+ method: "POST",
913
+ headers: {
914
+ ...this.headers,
915
+ "Accept": "text/event-stream"
916
+ },
917
+ body: JSON.stringify(payload)
918
+ });
919
+ if (!response.ok) {
920
+ const errorData = await response.json().catch(() => ({}));
921
+ yield { type: "error", error: errorData.error || `HTTP Error: ${response.status}` };
922
+ return;
923
+ }
924
+ const reader = response.body?.getReader();
925
+ const decoder = new TextDecoder();
926
+ let buffer = "";
927
+ if (!reader) {
928
+ yield { type: "error", error: "No response body" };
929
+ return;
930
+ }
931
+ while (true) {
932
+ const { done, value } = await reader.read();
933
+ if (done) break;
934
+ buffer += decoder.decode(value, { stream: true });
935
+ const lines = buffer.split("\n");
936
+ buffer = lines.pop() || "";
937
+ for (const line of lines) {
938
+ if (!line.startsWith("data: ")) continue;
939
+ const dataStr = line.slice(6);
940
+ if (dataStr === "[DONE]") {
941
+ yield { type: "done" };
942
+ continue;
943
+ }
944
+ try {
945
+ const parsed = JSON.parse(dataStr);
946
+ if (parsed.search_results && parsed.success === void 0) {
947
+ yield { type: "search_results", search_results: parsed.search_results };
948
+ } else if (parsed.choices) {
949
+ const delta = parsed.choices[0]?.delta || {};
950
+ const content = delta.content || "";
951
+ const finishReason = parsed.choices[0]?.finish_reason;
952
+ if (content || finishReason) {
953
+ yield { type: "content", content, finish_reason: finishReason };
954
+ }
955
+ } else if (parsed.success !== void 0) {
956
+ yield {
957
+ type: "metadata",
958
+ ai_tx_id: parsed.ai_tx_id,
959
+ original_query: parsed.original_query,
960
+ data_type: parsed.data_type,
961
+ search_results: parsed.search_results,
962
+ search_metadata: parsed.search_metadata,
963
+ ai_usage: parsed.ai_usage,
964
+ cost: parsed.cost
965
+ };
966
+ }
967
+ } catch {
968
+ continue;
969
+ }
970
+ }
971
+ }
972
+ } catch (e) {
973
+ yield { type: "error", error: e.message || "Stream failed" };
974
+ }
975
+ }
976
+ /**
977
+ * Create an error generator for streaming errors
978
+ */
979
+ async *createErrorGenerator(error) {
980
+ yield { type: "error", error };
981
+ }
882
982
  };
883
983
  // Annotate the CommonJS export names for ESM import in node:
884
984
  0 && (module.exports = {