exa-js 1.7.0 → 1.7.2

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.ts CHANGED
@@ -5,11 +5,11 @@
5
5
  /**
6
6
  * Type for API query parameters
7
7
  */
8
- type QueryParams = Record<string, string | number | boolean | string[] | undefined>;
8
+ type QueryParams$1 = Record<string, string | number | boolean | string[] | undefined>;
9
9
  /**
10
10
  * Type for API request body
11
11
  */
12
- interface RequestBody {
12
+ interface RequestBody$1 {
13
13
  [key: string]: unknown;
14
14
  }
15
15
  /**
@@ -44,13 +44,13 @@ declare class WebsetsBaseClient {
44
44
  * @returns The response JSON
45
45
  * @throws ExaError with API error details if the request fails
46
46
  */
47
- protected request<T = unknown>(endpoint: string, method?: string, data?: RequestBody, params?: QueryParams): Promise<T>;
47
+ protected request<T = unknown>(endpoint: string, method?: string, data?: RequestBody$1, params?: QueryParams$1): Promise<T>;
48
48
  /**
49
49
  * Helper to build pagination parameters
50
50
  * @param pagination The pagination parameters
51
51
  * @returns QueryParams object with pagination parameters
52
52
  */
53
- protected buildPaginationParams(pagination?: PaginationParams): QueryParams;
53
+ protected buildPaginationParams(pagination?: PaginationParams): QueryParams$1;
54
54
  }
55
55
 
56
56
  interface components {
@@ -1340,6 +1340,93 @@ declare class WebsetsClient extends WebsetsBaseClient {
1340
1340
  } | number): Promise<Webset>;
1341
1341
  }
1342
1342
 
1343
+ /**
1344
+ * Enum representing the status of a research task.
1345
+ */
1346
+ declare enum ResearchStatus {
1347
+ /** The research request has finished successfully. */
1348
+ completed = "completed",
1349
+ /** The research request failed. */
1350
+ failed = "failed"
1351
+ }
1352
+ /**
1353
+ * Response object returned from the research API.
1354
+ */
1355
+ type ResearchTaskResponse = {
1356
+ /** Unique identifier for the task. */
1357
+ id: string;
1358
+ /** Current status (may include future enum values served by the API). */
1359
+ status: ResearchStatus | string;
1360
+ /** Structured output that follows the user-provided schema (null while running). */
1361
+ output: Record<string, any> | null;
1362
+ /**
1363
+ * Citations collected while deriving each top-level field in `output`.
1364
+ * The key is the field name, the value is the list of `SearchResult`s that
1365
+ * were used to compute that field.
1366
+ */
1367
+ citations: Record<string, SearchResult<{}>[]>;
1368
+ };
1369
+
1370
+ type QueryParams = Record<string, string | number | boolean | string[] | undefined>;
1371
+ interface RequestBody {
1372
+ [key: string]: unknown;
1373
+ }
1374
+ /**
1375
+ * Base client class for all Research-related API clients
1376
+ */
1377
+ declare class ResearchBaseClient {
1378
+ protected client: Exa;
1379
+ /**
1380
+ * Initialize a new Research base client
1381
+ * @param client The Exa client instance
1382
+ */
1383
+ constructor(client: Exa);
1384
+ /**
1385
+ * Make a request to the Research API (prefixes all paths with `/research`).
1386
+ * @param endpoint The endpoint path, beginning with a slash (e.g. "/tasks").
1387
+ * @param method The HTTP method. Defaults to "POST".
1388
+ * @param data Optional request body
1389
+ * @param params Optional query parameters
1390
+ * @returns The parsed JSON response
1391
+ */
1392
+ protected request<T = unknown>(endpoint: string, method?: string, data?: RequestBody, params?: QueryParams): Promise<T>;
1393
+ }
1394
+
1395
+ /**
1396
+ * Client for interacting with the Research Tasks API.
1397
+ */
1398
+ declare class ResearchClient extends ResearchBaseClient {
1399
+ constructor(client: Exa);
1400
+ /**
1401
+ * Create and run a research task (blocking call).
1402
+ *
1403
+ * Both parameters are required and have fixed shapes:
1404
+ * 1. `input`
1405
+ * `{ instructions: string }`
1406
+ * • `instructions` – High-level guidance that tells the research agent what to do.
1407
+ * 2. `output`
1408
+ * defines the exact structure you expect back, and guides the research conducted by the agent.
1409
+ * `{ schema: JSONSchema }`.
1410
+ * The agent's response will be validated against this schema.
1411
+ *
1412
+ * @param input Object containing high-level research instructions.
1413
+ * @param output Object containing the expected output schema.
1414
+ * @returns The ResearchTaskResponse returned by the API.
1415
+ */
1416
+ createTask(input: {
1417
+ instructions: string;
1418
+ }, output: {
1419
+ schema: JSONSchema;
1420
+ }): Promise<ResearchTaskResponse>;
1421
+ /**
1422
+ * Retrieve a research task by ID.
1423
+ *
1424
+ * Not yet implemented server-side. Calling this will throw until the API is
1425
+ * available.
1426
+ */
1427
+ getTask(): Promise<ResearchTaskResponse>;
1428
+ }
1429
+
1343
1430
  /**
1344
1431
  * HTTP status codes
1345
1432
  */
@@ -1644,23 +1731,25 @@ type SearchResponse<T extends ContentsOptions> = {
1644
1731
  * @property {boolean} [text] - Whether to include text in the source results. Default false.
1645
1732
  * @property {"exa" | "exa-pro"} [model] - The model to use for generating the answer. Default "exa".
1646
1733
  * @property {string} [systemPrompt] - A system prompt to guide the LLM's behavior when generating the answer.
1734
+ * @property {Object} [outputSchema] - A JSON Schema specification for the structure you expect the output to take
1647
1735
  */
1648
1736
  type AnswerOptions = {
1649
1737
  stream?: boolean;
1650
1738
  text?: boolean;
1651
1739
  model?: "exa" | "exa-pro";
1652
1740
  systemPrompt?: string;
1741
+ outputSchema?: Record<string, unknown>;
1653
1742
  };
1654
1743
  /**
1655
1744
  * Represents an answer response object from the /answer endpoint.
1656
1745
  * @typedef {Object} AnswerResponse
1657
- * @property {string} answer - The generated answer text.
1746
+ * @property {string | Object} answer - The generated answer text (or an object matching `outputSchema`, if provided)
1658
1747
  * @property {SearchResult<{}>[]} citations - The sources used to generate the answer.
1659
1748
  * @property {CostDollars} [costDollars] - The cost breakdown for this request.
1660
1749
  * @property {string} [requestId] - Optional request ID for the answer.
1661
1750
  */
1662
1751
  type AnswerResponse = {
1663
- answer: string;
1752
+ answer: string | Record<string, unknown>;
1664
1753
  citations: SearchResult<{}>[];
1665
1754
  requestId?: string;
1666
1755
  costDollars?: CostDollars;
@@ -1692,29 +1781,6 @@ type AnswerStreamResponse = {
1692
1781
  answer?: string;
1693
1782
  citations?: SearchResult<{}>[];
1694
1783
  };
1695
- /**
1696
- * Enum representing the status of a research task.
1697
- */
1698
- declare enum ResearchStatus {
1699
- /** The research request has finished successfully. */
1700
- completed = "completed",
1701
- /** The research request failed. */
1702
- failed = "failed"
1703
- }
1704
- /**
1705
- * @typedef {Object} ResearchTaskResponse
1706
- * @property {string} id - The unique identifier of the research request.
1707
- * @property {ResearchStatus | string} status - The current status of the research request.
1708
- * @property {Record<string, any> | null} output - The structured output, if the research has completed.
1709
- * @property {SearchResult<{}>[]} citations - References used for the research.
1710
- */
1711
- type ResearchTaskResponse = {
1712
- id: string;
1713
- status: ResearchStatus | string;
1714
- output: Record<string, any> | null;
1715
- citations: SearchResult<{}>[];
1716
- };
1717
-
1718
1784
  /**
1719
1785
  * The Exa class encapsulates the API's endpoints.
1720
1786
  */
@@ -1725,6 +1791,10 @@ declare class Exa {
1725
1791
  * Websets API client
1726
1792
  */
1727
1793
  websets: WebsetsClient;
1794
+ /**
1795
+ * Research API client
1796
+ */
1797
+ research: ResearchClient;
1728
1798
  /**
1729
1799
  * Helper method to separate out the contents-specific options from the rest.
1730
1800
  */
@@ -1828,44 +1898,10 @@ declare class Exa {
1828
1898
  text?: boolean;
1829
1899
  model?: "exa" | "exa-pro";
1830
1900
  systemPrompt?: string;
1901
+ outputSchema?: Record<string, unknown>;
1831
1902
  }): AsyncGenerator<AnswerStreamChunk>;
1832
1903
  private processChunk;
1833
- /**
1834
- * Creates and runs a research task in a blocking manner.
1835
- *
1836
- * Both parameters are required and have fixed shapes:
1837
- * 1. `input`
1838
- * `{ instructions: string }`
1839
- * • `instructions` – High-level guidance that tells the research agent what to do.
1840
- * 2. `output`
1841
- * defines the exact structure you expect back, and guides the research conducted by the agent.
1842
- * `{ schema: JSONSchema }`.
1843
- * The agent’s response will be validated against this schema.
1844
- *
1845
- * @param {{ instructions: string }} input The research prompt.
1846
- * @param {{ schema: JSONSchema }} output The desired output schema.
1847
- * @returns {Promise<ResearchTaskResponse>} The research response.
1848
- *
1849
- * @example
1850
- * const response = await exa.researchTask(
1851
- * { instructions: "I need a few key facts about honey pot ants." },
1852
- * {
1853
- * schema: {
1854
- * type: "object",
1855
- * required: ["scientificName", "primaryRegions"],
1856
- * properties: {
1857
- * scientificName: { type: "string" },
1858
- * primaryRegions: { type: "string" },
1859
- * },
1860
- * },
1861
- * },
1862
- * );
1863
- */
1864
- researchTask(input: {
1865
- instructions: string;
1866
- }, output: {
1867
- schema: JSONSchema;
1868
- }): Promise<ResearchTaskResponse>;
1904
+ private parseSSEStream;
1869
1905
  }
1870
1906
 
1871
- export { type AnswerOptions, type AnswerResponse, type AnswerStreamChunk, type AnswerStreamResponse, type BaseSearchOptions, type ContentsOptions, type ContentsResultComponent, type CostDollars, type CostDollarsContents, type CostDollarsSeearch, type CreateEnrichmentParameters, CreateEnrichmentParametersFormat, type CreateWebhookParameters, type CreateWebsetParameters, type CreateWebsetSearchParameters, CreateWebsetSearchParametersBehaviour, type Default, type EnrichmentResult, type Event, EventType, Exa, ExaError, type ExtrasOptions, type ExtrasResponse, type FindSimilarOptions, type GetWebsetResponse, type HighlightsContentsOptions, type HighlightsResponse, HttpStatusCode, type JSONSchema, type ListEventsResponse, type ListWebhooksOptions, type ListWebhooksResponse, type ListWebsetItemResponse, type ListWebsetsOptions, type ListWebsetsResponse, type LivecrawlOptions, type RegularSearchOptions, ResearchStatus, type ResearchTaskResponse, type SearchResponse, type SearchResult, type SubpagesResponse, type SummaryContentsOptions, type SummaryResponse, type TextContentsOptions, type TextResponse, type UpdateWebhookParameters, type UpdateWebsetRequest, type Webhook, WebhookStatus, type Webset, type WebsetEnrichment, WebsetEnrichmentFormat, WebsetEnrichmentStatus, WebsetEnrichmentsClient, type WebsetItem, WebsetItemEvaluationSatisfied, WebsetItemSource, WebsetItemsClient, type WebsetSearch, WebsetSearchCanceledReason, WebsetSearchStatus, WebsetSearchesClient, WebsetStatus, WebsetWebhooksClient, WebsetsClient, Exa as default };
1907
+ export { type AnswerOptions, type AnswerResponse, type AnswerStreamChunk, type AnswerStreamResponse, type BaseSearchOptions, type ContentsOptions, type ContentsResultComponent, type CostDollars, type CostDollarsContents, type CostDollarsSeearch, type CreateEnrichmentParameters, CreateEnrichmentParametersFormat, type CreateWebhookParameters, type CreateWebsetParameters, type CreateWebsetSearchParameters, CreateWebsetSearchParametersBehaviour, type Default, type EnrichmentResult, type Event, EventType, Exa, ExaError, type ExtrasOptions, type ExtrasResponse, type FindSimilarOptions, type GetWebsetResponse, type HighlightsContentsOptions, type HighlightsResponse, HttpStatusCode, type JSONSchema, type ListEventsResponse, type ListWebhooksOptions, type ListWebhooksResponse, type ListWebsetItemResponse, type ListWebsetsOptions, type ListWebsetsResponse, type LivecrawlOptions, type RegularSearchOptions, ResearchClient, ResearchStatus, type ResearchTaskResponse, type SearchResponse, type SearchResult, type SubpagesResponse, type SummaryContentsOptions, type SummaryResponse, type TextContentsOptions, type TextResponse, type UpdateWebhookParameters, type UpdateWebsetRequest, type Webhook, WebhookStatus, type Webset, type WebsetEnrichment, WebsetEnrichmentFormat, WebsetEnrichmentStatus, WebsetEnrichmentsClient, type WebsetItem, WebsetItemEvaluationSatisfied, WebsetItemSource, WebsetItemsClient, type WebsetSearch, WebsetSearchCanceledReason, WebsetSearchStatus, WebsetSearchesClient, WebsetStatus, WebsetWebhooksClient, WebsetsClient, Exa as default };
package/dist/index.js CHANGED
@@ -36,6 +36,7 @@ __export(index_exports, {
36
36
  Exa: () => Exa2,
37
37
  ExaError: () => ExaError,
38
38
  HttpStatusCode: () => HttpStatusCode,
39
+ ResearchClient: () => ResearchClient,
39
40
  ResearchStatus: () => ResearchStatus,
40
41
  WebhookStatus: () => WebhookStatus,
41
42
  WebsetEnrichmentFormat: () => WebsetEnrichmentFormat,
@@ -690,14 +691,76 @@ var WebsetsClient = class extends WebsetsBaseClient {
690
691
  }
691
692
  };
692
693
 
693
- // src/index.ts
694
- var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : import_cross_fetch.default;
695
- var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : import_cross_fetch.Headers;
694
+ // src/research/base.ts
695
+ var ResearchBaseClient = class {
696
+ /**
697
+ * Initialize a new Research base client
698
+ * @param client The Exa client instance
699
+ */
700
+ constructor(client) {
701
+ this.client = client;
702
+ }
703
+ /**
704
+ * Make a request to the Research API (prefixes all paths with `/research`).
705
+ * @param endpoint The endpoint path, beginning with a slash (e.g. "/tasks").
706
+ * @param method The HTTP method. Defaults to "POST".
707
+ * @param data Optional request body
708
+ * @param params Optional query parameters
709
+ * @returns The parsed JSON response
710
+ */
711
+ async request(endpoint, method = "POST", data, params) {
712
+ return this.client.request(`/research${endpoint}`, method, data, params);
713
+ }
714
+ };
715
+
716
+ // src/research/client.ts
717
+ var ResearchClient = class extends ResearchBaseClient {
718
+ constructor(client) {
719
+ super(client);
720
+ }
721
+ /**
722
+ * Create and run a research task (blocking call).
723
+ *
724
+ * Both parameters are required and have fixed shapes:
725
+ * 1. `input`
726
+ * `{ instructions: string }`
727
+ * • `instructions` – High-level guidance that tells the research agent what to do.
728
+ * 2. `output`
729
+ * defines the exact structure you expect back, and guides the research conducted by the agent.
730
+ * `{ schema: JSONSchema }`.
731
+ * The agent's response will be validated against this schema.
732
+ *
733
+ * @param input Object containing high-level research instructions.
734
+ * @param output Object containing the expected output schema.
735
+ * @returns The ResearchTaskResponse returned by the API.
736
+ */
737
+ async createTask(input, output) {
738
+ return this.request("/tasks", "POST", {
739
+ input,
740
+ output
741
+ });
742
+ }
743
+ /**
744
+ * Retrieve a research task by ID.
745
+ *
746
+ * Not yet implemented server-side. Calling this will throw until the API is
747
+ * available.
748
+ */
749
+ async getTask() {
750
+ throw new Error("getTask is not implemented yet.");
751
+ }
752
+ };
753
+
754
+ // src/research/types.ts
696
755
  var ResearchStatus = /* @__PURE__ */ ((ResearchStatus2) => {
697
756
  ResearchStatus2["completed"] = "completed";
698
757
  ResearchStatus2["failed"] = "failed";
699
758
  return ResearchStatus2;
700
759
  })(ResearchStatus || {});
760
+
761
+ // src/index.ts
762
+ var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : import_cross_fetch.default;
763
+ var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : import_cross_fetch.Headers;
701
764
  var Exa2 = class {
702
765
  /**
703
766
  * Helper method to separate out the contents-specific options from the rest.
@@ -755,6 +818,7 @@ var Exa2 = class {
755
818
  "User-Agent": "exa-node 1.4.0"
756
819
  });
757
820
  this.websets = new WebsetsClient(this);
821
+ this.research = new ResearchClient(this);
758
822
  }
759
823
  /**
760
824
  * Makes a request to the Exa API.
@@ -804,6 +868,10 @@ var Exa2 = class {
804
868
  errorData.path
805
869
  );
806
870
  }
871
+ const contentType = response.headers.get("content-type") || "";
872
+ if (contentType.includes("text/event-stream")) {
873
+ return await this.parseSSEStream(response);
874
+ }
807
875
  return await response.json();
808
876
  }
809
877
  /**
@@ -915,7 +983,8 @@ var Exa2 = class {
915
983
  stream: false,
916
984
  text: options?.text ?? false,
917
985
  model: options?.model ?? "exa",
918
- systemPrompt: options?.systemPrompt
986
+ systemPrompt: options?.systemPrompt,
987
+ outputSchema: options?.outputSchema
919
988
  };
920
989
  return await this.request("/answer", "POST", requestBody);
921
990
  }
@@ -944,7 +1013,8 @@ var Exa2 = class {
944
1013
  text: options?.text ?? false,
945
1014
  stream: true,
946
1015
  model: options?.model ?? "exa",
947
- systemPrompt: options?.systemPrompt
1016
+ systemPrompt: options?.systemPrompt,
1017
+ outputSchema: options?.outputSchema
948
1018
  };
949
1019
  const response = await fetchImpl(this.baseURL + "/answer", {
950
1020
  method: "POST",
@@ -1025,47 +1095,76 @@ var Exa2 = class {
1025
1095
  }
1026
1096
  return { content, citations };
1027
1097
  }
1028
- /**
1029
- * Creates and runs a research task in a blocking manner.
1030
- *
1031
- * Both parameters are required and have fixed shapes:
1032
- * 1. `input`
1033
- * `{ instructions: string }`
1034
- * • `instructions` High-level guidance that tells the research agent what to do.
1035
- * 2. `output`
1036
- * defines the exact structure you expect back, and guides the research conducted by the agent.
1037
- * `{ schema: JSONSchema }`.
1038
- * The agent’s response will be validated against this schema.
1039
- *
1040
- * @param {{ instructions: string }} input The research prompt.
1041
- * @param {{ schema: JSONSchema }} output The desired output schema.
1042
- * @returns {Promise<ResearchTaskResponse>} The research response.
1043
- *
1044
- * @example
1045
- * const response = await exa.researchTask(
1046
- * { instructions: "I need a few key facts about honey pot ants." },
1047
- * {
1048
- * schema: {
1049
- * type: "object",
1050
- * required: ["scientificName", "primaryRegions"],
1051
- * properties: {
1052
- * scientificName: { type: "string" },
1053
- * primaryRegions: { type: "string" },
1054
- * },
1055
- * },
1056
- * },
1057
- * );
1058
- */
1059
- async researchTask(input, output) {
1060
- const body = {
1061
- input,
1062
- output
1063
- };
1064
- return await this.request(
1065
- "/research/tasks",
1066
- "POST",
1067
- body
1068
- );
1098
+ async parseSSEStream(response) {
1099
+ const reader = response.body?.getReader();
1100
+ if (!reader) {
1101
+ throw new ExaError(
1102
+ "No response body available for streaming.",
1103
+ 500,
1104
+ (/* @__PURE__ */ new Date()).toISOString()
1105
+ );
1106
+ }
1107
+ const decoder = new TextDecoder();
1108
+ let buffer = "";
1109
+ return new Promise(async (resolve, reject) => {
1110
+ try {
1111
+ while (true) {
1112
+ const { done, value } = await reader.read();
1113
+ if (done) break;
1114
+ buffer += decoder.decode(value, { stream: true });
1115
+ const lines = buffer.split("\n");
1116
+ buffer = lines.pop() || "";
1117
+ for (const line of lines) {
1118
+ if (!line.startsWith("data: ")) continue;
1119
+ const jsonStr = line.replace(/^data:\s*/, "").trim();
1120
+ if (!jsonStr || jsonStr === "[DONE]") {
1121
+ continue;
1122
+ }
1123
+ let chunk;
1124
+ try {
1125
+ chunk = JSON.parse(jsonStr);
1126
+ } catch {
1127
+ continue;
1128
+ }
1129
+ switch (chunk.tag) {
1130
+ case "complete":
1131
+ reader.releaseLock();
1132
+ resolve(chunk.data);
1133
+ return;
1134
+ case "error": {
1135
+ const message = chunk.error?.message || "Unknown error";
1136
+ reader.releaseLock();
1137
+ reject(
1138
+ new ExaError(
1139
+ message,
1140
+ 500 /* InternalServerError */,
1141
+ (/* @__PURE__ */ new Date()).toISOString()
1142
+ )
1143
+ );
1144
+ return;
1145
+ }
1146
+ // 'progress' and any other tags are ignored for the blocking variant
1147
+ default:
1148
+ break;
1149
+ }
1150
+ }
1151
+ }
1152
+ reject(
1153
+ new ExaError(
1154
+ "Stream ended without a completion event.",
1155
+ 500 /* InternalServerError */,
1156
+ (/* @__PURE__ */ new Date()).toISOString()
1157
+ )
1158
+ );
1159
+ } catch (err) {
1160
+ reject(err);
1161
+ } finally {
1162
+ try {
1163
+ reader.releaseLock();
1164
+ } catch {
1165
+ }
1166
+ }
1167
+ });
1069
1168
  }
1070
1169
  };
1071
1170
  var index_default = Exa2;
@@ -1077,6 +1176,7 @@ var index_default = Exa2;
1077
1176
  Exa,
1078
1177
  ExaError,
1079
1178
  HttpStatusCode,
1179
+ ResearchClient,
1080
1180
  ResearchStatus,
1081
1181
  WebhookStatus,
1082
1182
  WebsetEnrichmentFormat,