exa-js 2.5.1-beta.0 → 2.5.1-beta.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.js CHANGED
@@ -75,7 +75,7 @@ var import_cross_fetch = __toESM(require("cross-fetch"));
75
75
  // package.json
76
76
  var package_default = {
77
77
  name: "exa-js",
78
- version: "2.5.1-beta.0",
78
+ version: "2.5.1-beta.1",
79
79
  description: "Exa SDK for Node.js and the browser",
80
80
  publishConfig: {
81
81
  access: "public"
@@ -1440,13 +1440,7 @@ var WebsetsBaseClient2 = class {
1440
1440
  }
1441
1441
  /** Make a request to the API, prepending `/websets` to the path. */
1442
1442
  async request(endpoint, method = "POST", data, params, headers) {
1443
- return this.client.request(
1444
- `/websets${endpoint}`,
1445
- method,
1446
- data,
1447
- params,
1448
- headers
1449
- );
1443
+ return this.client.request(`/websets${endpoint}`, method, data, params, headers);
1450
1444
  }
1451
1445
  buildPaginationParams(pagination) {
1452
1446
  const params = {};
@@ -1464,50 +1458,50 @@ var WebsetItemsClient2 = class extends WebsetsBaseClient2 {
1464
1458
  return this.request(`/v0/websets/${websetId}/items/${id}`, "DELETE");
1465
1459
  }
1466
1460
  async list(websetId, options) {
1467
- const queryParams = {
1468
- ...this.buildPaginationParams(options),
1469
- sourceId: options?.sourceId
1470
- };
1471
- return this.request(
1472
- `/v0/websets/${websetId}/items`,
1473
- "GET",
1474
- void 0,
1475
- queryParams
1476
- );
1461
+ const queryParams = { ...this.buildPaginationParams(options), sourceId: options?.sourceId };
1462
+ return this.request(`/v0/websets/${websetId}/items`, "GET", void 0, queryParams);
1463
+ }
1464
+ /** Iterate through all items in a Webset, handling pagination automatically. */
1465
+ async *listAll(websetId, options) {
1466
+ let cursor = void 0;
1467
+ const pageOptions = options ? { ...options } : {};
1468
+ while (true) {
1469
+ const response = await this.list(websetId, { ...pageOptions, cursor });
1470
+ for (const item of response.data) {
1471
+ yield item;
1472
+ }
1473
+ if (!response.hasMore || !response.nextCursor) {
1474
+ break;
1475
+ }
1476
+ cursor = response.nextCursor;
1477
+ }
1478
+ }
1479
+ /** Collect all items from a Webset into an array. */
1480
+ async getAll(websetId, options) {
1481
+ const items = [];
1482
+ for await (const item of this.listAll(websetId, options)) {
1483
+ items.push(item);
1484
+ }
1485
+ return items;
1477
1486
  }
1478
1487
  };
1479
1488
  var WebsetSearchesClient2 = class extends WebsetsBaseClient2 {
1480
1489
  async create(websetId, params, options) {
1481
- return this.request(
1482
- `/v0/websets/${websetId}/searches`,
1483
- "POST",
1484
- { ...params },
1485
- void 0,
1486
- options?.headers
1487
- );
1490
+ return this.request(`/v0/websets/${websetId}/searches`, "POST", { ...params }, void 0, options?.headers);
1488
1491
  }
1489
1492
  async get(websetId, id) {
1490
1493
  return this.request(`/v0/websets/${websetId}/searches/${id}`, "GET");
1491
1494
  }
1492
1495
  async cancel(websetId, id) {
1493
- return this.request(
1494
- `/v0/websets/${websetId}/searches/${id}/cancel`,
1495
- "POST"
1496
- );
1496
+ return this.request(`/v0/websets/${websetId}/searches/${id}/cancel`, "POST");
1497
1497
  }
1498
1498
  };
1499
1499
  var WebsetEnrichmentsClient2 = class extends WebsetsBaseClient2 {
1500
1500
  async create(websetId, params) {
1501
- return this.request(`/v0/websets/${websetId}/enrichments`, "POST", {
1502
- ...params
1503
- });
1501
+ return this.request(`/v0/websets/${websetId}/enrichments`, "POST", { ...params });
1504
1502
  }
1505
1503
  async update(websetId, id, params) {
1506
- return this.request(
1507
- `/v0/websets/${websetId}/enrichments/${id}`,
1508
- "PATCH",
1509
- { ...params }
1510
- );
1504
+ return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "PATCH", { ...params });
1511
1505
  }
1512
1506
  async get(websetId, id) {
1513
1507
  return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "GET");
@@ -1516,20 +1510,12 @@ var WebsetEnrichmentsClient2 = class extends WebsetsBaseClient2 {
1516
1510
  return this.request(`/v0/websets/${websetId}/enrichments/${id}`, "DELETE");
1517
1511
  }
1518
1512
  async cancel(websetId, id) {
1519
- return this.request(
1520
- `/v0/websets/${websetId}/enrichments/${id}/cancel`,
1521
- "POST"
1522
- );
1513
+ return this.request(`/v0/websets/${websetId}/enrichments/${id}/cancel`, "POST");
1523
1514
  }
1524
1515
  };
1525
1516
  var EventsClient2 = class extends WebsetsBaseClient2 {
1526
1517
  async list(options) {
1527
- const queryParams = {
1528
- ...this.buildPaginationParams(options),
1529
- types: options?.types,
1530
- createdBefore: options?.createdBefore,
1531
- createdAfter: options?.createdAfter
1532
- };
1518
+ const queryParams = { ...this.buildPaginationParams(options), types: options?.types, createdBefore: options?.createdBefore, createdAfter: options?.createdAfter };
1533
1519
  return this.request("/v0/events", "GET", void 0, queryParams);
1534
1520
  }
1535
1521
  async get(id) {
@@ -1553,10 +1539,7 @@ var WebsetMonitorsClient2 = class extends WebsetsBaseClient2 {
1553
1539
  return this.request("/v0/monitors", "POST", { ...params });
1554
1540
  }
1555
1541
  async list(options) {
1556
- const queryParams = {
1557
- ...this.buildPaginationParams(options),
1558
- websetId: options?.websetId
1559
- };
1542
+ const queryParams = { ...this.buildPaginationParams(options), websetId: options?.websetId };
1560
1543
  return this.request("/v0/monitors", "GET", void 0, queryParams);
1561
1544
  }
1562
1545
  async get(id) {
@@ -1568,6 +1551,29 @@ var WebsetMonitorsClient2 = class extends WebsetsBaseClient2 {
1568
1551
  async delete(id) {
1569
1552
  return this.request(`/v0/monitors/${id}`, "DELETE");
1570
1553
  }
1554
+ /** Iterate through all monitors, handling pagination automatically. */
1555
+ async *listAll(options) {
1556
+ let cursor = void 0;
1557
+ const pageOptions = options ? { ...options } : {};
1558
+ while (true) {
1559
+ const response = await this.list({ ...pageOptions, cursor });
1560
+ for (const monitor of response.data) {
1561
+ yield monitor;
1562
+ }
1563
+ if (!response.hasMore || !response.nextCursor) {
1564
+ break;
1565
+ }
1566
+ cursor = response.nextCursor;
1567
+ }
1568
+ }
1569
+ /** Collect all monitors into an array. */
1570
+ async getAll(options) {
1571
+ const monitors = [];
1572
+ for await (const monitor of this.listAll(options)) {
1573
+ monitors.push(monitor);
1574
+ }
1575
+ return monitors;
1576
+ }
1571
1577
  };
1572
1578
  var WebsetWebhooksClient2 = class extends WebsetsBaseClient2 {
1573
1579
  async create(params) {
@@ -1587,17 +1593,8 @@ var WebsetWebhooksClient2 = class extends WebsetsBaseClient2 {
1587
1593
  return this.request(`/v0/webhooks/${id}`, "DELETE");
1588
1594
  }
1589
1595
  async listAttempts(id, options) {
1590
- const queryParams = {
1591
- ...this.buildPaginationParams(options),
1592
- eventType: options?.eventType,
1593
- successful: options?.successful
1594
- };
1595
- return this.request(
1596
- `/v0/webhooks/${id}/attempts`,
1597
- "GET",
1598
- void 0,
1599
- queryParams
1600
- );
1596
+ const queryParams = { ...this.buildPaginationParams(options), eventType: options?.eventType, successful: options?.successful };
1597
+ return this.request(`/v0/webhooks/${id}/attempts`, "GET", void 0, queryParams);
1601
1598
  }
1602
1599
  };
1603
1600
  var ImportsClient2 = class extends WebsetsBaseClient2 {
@@ -1630,19 +1627,10 @@ var WebsetsClient2 = class extends WebsetsBaseClient2 {
1630
1627
  this.imports = new ImportsClient2(client);
1631
1628
  }
1632
1629
  async create(params, options) {
1633
- return this.request(
1634
- "/v0/websets",
1635
- "POST",
1636
- { ...params },
1637
- void 0,
1638
- options?.headers
1639
- );
1630
+ return this.request("/v0/websets", "POST", { ...params }, void 0, options?.headers);
1640
1631
  }
1641
1632
  async list(options) {
1642
- const queryParams = {
1643
- ...this.buildPaginationParams(options),
1644
- search: options?.search
1645
- };
1633
+ const queryParams = { ...this.buildPaginationParams(options), search: options?.search };
1646
1634
  return this.request("/v0/websets", "GET", void 0, queryParams);
1647
1635
  }
1648
1636
  async get(id, options) {
@@ -1660,12 +1648,30 @@ var WebsetsClient2 = class extends WebsetsBaseClient2 {
1660
1648
  }
1661
1649
  async preview(params, options) {
1662
1650
  const queryParams = { search: options?.search };
1663
- return this.request(
1664
- "/v0/websets/preview",
1665
- "POST",
1666
- { ...params },
1667
- queryParams
1668
- );
1651
+ return this.request("/v0/websets/preview", "POST", { ...params }, queryParams);
1652
+ }
1653
+ /** Iterate through all Websets, handling pagination automatically. */
1654
+ async *listAll(options) {
1655
+ let cursor = void 0;
1656
+ const pageOptions = options ? { ...options } : {};
1657
+ while (true) {
1658
+ const response = await this.list({ ...pageOptions, cursor });
1659
+ for (const webset of response.data) {
1660
+ yield webset;
1661
+ }
1662
+ if (!response.hasMore || !response.nextCursor) {
1663
+ break;
1664
+ }
1665
+ cursor = response.nextCursor;
1666
+ }
1667
+ }
1668
+ /** Collect all Websets into an array. */
1669
+ async getAll(options) {
1670
+ const websets = [];
1671
+ for await (const webset of this.listAll(options)) {
1672
+ websets.push(webset);
1673
+ }
1674
+ return websets;
1669
1675
  }
1670
1676
  /** Poll until a Webset reaches idle status. */
1671
1677
  async waitUntilIdle(id, options) {
@@ -1685,9 +1691,7 @@ var WebsetsClient2 = class extends WebsetsBaseClient2 {
1685
1691
  if (onPoll) onPoll(webset.status);
1686
1692
  if (webset.status === "idle") return webset;
1687
1693
  if (timeout && Date.now() - startTime > timeout) {
1688
- throw new Error(
1689
- `Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`
1690
- );
1694
+ throw new Error(`Webset ${id} did not reach idle state within ${timeout}ms. Current status: ${webset.status}`);
1691
1695
  }
1692
1696
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
1693
1697
  }
@@ -1706,12 +1710,7 @@ var ResearchBaseClient2 = class {
1706
1710
  }
1707
1711
  /** Make a request to the API, prepending `/research/v1` to the path. */
1708
1712
  async request(endpoint, method = "POST", data, params) {
1709
- return this.client.request(
1710
- `/research/v1${endpoint}`,
1711
- method,
1712
- data,
1713
- params
1714
- );
1713
+ return this.client.request(`/research/v1${endpoint}`, method, data, params);
1715
1714
  }
1716
1715
  buildPaginationParams(pagination) {
1717
1716
  const params = {};
@@ -1745,14 +1744,8 @@ var ResearchClient2 = class extends ResearchBaseClient2 {
1745
1744
  /** Get a research request by ID. */
1746
1745
  async get(researchId, options) {
1747
1746
  const params = {};
1748
- if (options?.events !== void 0)
1749
- params.events = options.events.toString();
1750
- return this.client.request(
1751
- `/research/v1/${researchId}`,
1752
- "GET",
1753
- void 0,
1754
- params
1755
- );
1747
+ if (options?.events !== void 0) params.events = options.events.toString();
1748
+ return this.client.request(`/research/v1/${researchId}`, "GET", void 0, params);
1756
1749
  }
1757
1750
  /** Poll a research request until it reaches a terminal state (completed, failed, or canceled). */
1758
1751
  async pollUntilFinished(researchId, options) {
@@ -1763,9 +1756,7 @@ var ResearchClient2 = class extends ResearchBaseClient2 {
1763
1756
  let consecutiveFailures = 0;
1764
1757
  while (true) {
1765
1758
  try {
1766
- const research = await this.get(researchId, {
1767
- events: options?.events
1768
- });
1759
+ const research = await this.get(researchId, { events: options?.events });
1769
1760
  consecutiveFailures = 0;
1770
1761
  if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
1771
1762
  return research;
@@ -1773,15 +1764,11 @@ var ResearchClient2 = class extends ResearchBaseClient2 {
1773
1764
  } catch (err) {
1774
1765
  consecutiveFailures += 1;
1775
1766
  if (consecutiveFailures >= maxConsecutiveFailures) {
1776
- throw new Error(
1777
- `Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`
1778
- );
1767
+ throw new Error(`Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`);
1779
1768
  }
1780
1769
  }
1781
1770
  if (Date.now() - startTime > timeoutMs) {
1782
- throw new Error(
1783
- `Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`
1784
- );
1771
+ throw new Error(`Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`);
1785
1772
  }
1786
1773
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
1787
1774
  }
@@ -1789,19 +1776,20 @@ var ResearchClient2 = class extends ResearchBaseClient2 {
1789
1776
  };
1790
1777
 
1791
1778
  // src/nova/client.ts
1792
- var CONTENTS_FIELDS = /* @__PURE__ */ new Set([
1793
- "text",
1794
- "highlights",
1795
- "summary",
1796
- "subpages",
1797
- "subpageTarget",
1798
- "extras",
1799
- "livecrawl",
1800
- "livecrawlTimeout",
1801
- "maxAgeHours",
1802
- "filterEmptyResults",
1803
- "context"
1804
- ]);
1779
+ function isRecord(value) {
1780
+ return value != null && typeof value === "object" && !Array.isArray(value);
1781
+ }
1782
+ var ExaError2 = class extends Error {
1783
+ constructor(message, statusCode, timestamp, path, details) {
1784
+ super(message);
1785
+ this.name = "ExaError";
1786
+ this.statusCode = statusCode;
1787
+ this.timestamp = timestamp;
1788
+ this.path = path;
1789
+ this.details = details;
1790
+ }
1791
+ };
1792
+ var CONTENTS_FIELDS = /* @__PURE__ */ new Set(["text", "highlights", "summary", "subpages", "subpageTarget", "extras", "livecrawl", "livecrawlTimeout", "maxAgeHours", "filterEmptyResults", "context"]);
1805
1793
  var DEFAULT_MAX_CHARACTERS = 1e4;
1806
1794
  var Exa2 = class {
1807
1795
  constructor(apiKey, baseURL = "https://api.exa.ai") {
@@ -1809,8 +1797,9 @@ var Exa2 = class {
1809
1797
  if (!apiKey) {
1810
1798
  apiKey = typeof process !== "undefined" ? process.env?.EXA_API_KEY : void 0;
1811
1799
  if (!apiKey) {
1812
- throw new Error(
1813
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)"
1800
+ throw new ExaError2(
1801
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
1802
+ 401
1814
1803
  );
1815
1804
  }
1816
1805
  }
@@ -1823,21 +1812,8 @@ var Exa2 = class {
1823
1812
  }
1824
1813
  /** Make a request to the Exa API. Used by sub-clients and available for direct use. */
1825
1814
  async request(endpoint, method, body, params, headers) {
1826
- let url = `${this.baseURL}${endpoint}`;
1815
+ const url = this.buildRequestUrl(endpoint, params);
1827
1816
  const normalizedBody = this.normalizeCategoryInBody(body);
1828
- if (params && Object.keys(params).length > 0) {
1829
- const searchParams = new URLSearchParams();
1830
- for (const [key, value] of Object.entries(params)) {
1831
- if (Array.isArray(value)) {
1832
- for (const item of value) {
1833
- searchParams.append(key, item);
1834
- }
1835
- } else if (value !== void 0) {
1836
- searchParams.append(key, String(value));
1837
- }
1838
- }
1839
- url += `?${searchParams.toString()}`;
1840
- }
1841
1817
  const combinedHeaders = headers ? { ...this.headers, ...headers } : this.headers;
1842
1818
  const response = await fetch(url, {
1843
1819
  method,
@@ -1845,28 +1821,14 @@ var Exa2 = class {
1845
1821
  body: normalizedBody ? JSON.stringify(normalizedBody) : void 0
1846
1822
  });
1847
1823
  if (!response.ok) {
1848
- const text = await response.text();
1849
- throw new Error(`Exa API error ${response.status}: ${text}`);
1824
+ throw await this.toExaError(response, endpoint);
1850
1825
  }
1851
1826
  return await response.json();
1852
1827
  }
1853
1828
  /** Make a raw request returning the Response object directly. */
1854
1829
  async rawRequest(endpoint, method = "POST", body, params) {
1855
- let url = `${this.baseURL}${endpoint}`;
1830
+ const url = this.buildRequestUrl(endpoint, params);
1856
1831
  const normalizedBody = this.normalizeCategoryInBody(body);
1857
- if (params && Object.keys(params).length > 0) {
1858
- const searchParams = new URLSearchParams();
1859
- for (const [key, value] of Object.entries(params)) {
1860
- if (Array.isArray(value)) {
1861
- for (const item of value) {
1862
- searchParams.append(key, item);
1863
- }
1864
- } else if (value !== void 0) {
1865
- searchParams.append(key, String(value));
1866
- }
1867
- }
1868
- url += `?${searchParams.toString()}`;
1869
- }
1870
1832
  return fetch(url, {
1871
1833
  method,
1872
1834
  headers: this.headers,
@@ -1880,6 +1842,116 @@ var Exa2 = class {
1880
1842
  }
1881
1843
  return { ...body, category: body.category.replace(/ /g, "_") };
1882
1844
  }
1845
+ buildRequestUrl(endpoint, params) {
1846
+ let url = `${this.baseURL}${endpoint}`;
1847
+ if (params == null || Object.keys(params).length === 0) {
1848
+ return url;
1849
+ }
1850
+ const searchParams = new URLSearchParams();
1851
+ for (const [key, value] of Object.entries(params)) {
1852
+ if (Array.isArray(value)) {
1853
+ for (const item of value) {
1854
+ searchParams.append(key, item);
1855
+ }
1856
+ } else if (value !== void 0) {
1857
+ searchParams.append(key, String(value));
1858
+ }
1859
+ }
1860
+ url += `?${searchParams.toString()}`;
1861
+ return url;
1862
+ }
1863
+ tryParseJsonRecord(text) {
1864
+ if (text.length === 0) {
1865
+ return null;
1866
+ }
1867
+ try {
1868
+ const parsed = JSON.parse(text);
1869
+ return isRecord(parsed) ? parsed : null;
1870
+ } catch {
1871
+ return null;
1872
+ }
1873
+ }
1874
+ async toExaError(response, endpoint) {
1875
+ const text = await response.text();
1876
+ const parsed = this.tryParseJsonRecord(text);
1877
+ const statusCode = parsed != null && typeof parsed.statusCode === "number" ? parsed.statusCode : response.status;
1878
+ const timestamp = parsed != null && typeof parsed.timestamp === "string" ? parsed.timestamp : void 0;
1879
+ const path = parsed != null && typeof parsed.path === "string" ? parsed.path : endpoint;
1880
+ const errorMessage = parsed != null && typeof parsed.error === "string" ? parsed.error : void 0;
1881
+ const detailMessage = parsed != null && typeof parsed.message === "string" ? parsed.message : void 0;
1882
+ let message;
1883
+ if (errorMessage != null && detailMessage != null) {
1884
+ message = `${errorMessage}. ${detailMessage}`;
1885
+ } else if (errorMessage != null) {
1886
+ message = errorMessage;
1887
+ } else if (detailMessage != null) {
1888
+ message = detailMessage;
1889
+ } else if (text.length > 0) {
1890
+ message = text;
1891
+ } else {
1892
+ message = `Exa API error ${response.status}`;
1893
+ }
1894
+ return new ExaError2(message, statusCode, timestamp, path, parsed ?? text);
1895
+ }
1896
+ parseAnswerStreamLine(line) {
1897
+ if (!line.startsWith("data:")) {
1898
+ return null;
1899
+ }
1900
+ const jsonStr = line.replace(/^data:\s*/, "").trim();
1901
+ if (jsonStr.length === 0 || jsonStr === "[DONE]") {
1902
+ return null;
1903
+ }
1904
+ let parsedChunk;
1905
+ try {
1906
+ parsedChunk = JSON.parse(jsonStr);
1907
+ } catch {
1908
+ return null;
1909
+ }
1910
+ if (!isRecord(parsedChunk)) {
1911
+ return null;
1912
+ }
1913
+ let content;
1914
+ const choices = parsedChunk.choices;
1915
+ if (Array.isArray(choices) && choices.length > 0 && isRecord(choices[0])) {
1916
+ const delta = choices[0].delta;
1917
+ if (isRecord(delta) && typeof delta.content === "string") {
1918
+ content = delta.content;
1919
+ }
1920
+ }
1921
+ let citations;
1922
+ if (Array.isArray(parsedChunk.citations)) {
1923
+ const normalized = [];
1924
+ for (const citation of parsedChunk.citations) {
1925
+ if (!isRecord(citation)) {
1926
+ continue;
1927
+ }
1928
+ const id = typeof citation.id === "string" ? citation.id : void 0;
1929
+ const url = typeof citation.url === "string" ? citation.url : void 0;
1930
+ const title = typeof citation.title === "string" ? citation.title : void 0;
1931
+ const publishedDate = typeof citation.publishedDate === "string" ? citation.publishedDate : void 0;
1932
+ const author = typeof citation.author === "string" ? citation.author : void 0;
1933
+ const text = typeof citation.text === "string" ? citation.text : void 0;
1934
+ normalized.push({
1935
+ ...id != null ? { id } : {},
1936
+ ...url != null ? { url } : {},
1937
+ ...title != null ? { title } : {},
1938
+ ...publishedDate != null ? { publishedDate } : {},
1939
+ ...author != null ? { author } : {},
1940
+ ...text != null ? { text } : {}
1941
+ });
1942
+ }
1943
+ if (normalized.length > 0) {
1944
+ citations = normalized;
1945
+ }
1946
+ }
1947
+ if (content == null && (citations == null || citations.length === 0)) {
1948
+ return null;
1949
+ }
1950
+ return {
1951
+ ...content != null ? { content } : {},
1952
+ ...citations != null ? { citations } : {}
1953
+ };
1954
+ }
1883
1955
  /** Separate content-specific options from search/filter options. */
1884
1956
  extractContentsOptions(options) {
1885
1957
  const contentsOptions = {};
@@ -1901,11 +1973,7 @@ var Exa2 = class {
1901
1973
  search(query, options) {
1902
1974
  let body;
1903
1975
  if (options === void 0 || !("contents" in options)) {
1904
- body = {
1905
- query,
1906
- ...options,
1907
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
1908
- };
1976
+ body = { query, ...options, contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } } };
1909
1977
  } else if (options.contents === false || options.contents === null || options.contents === void 0) {
1910
1978
  const { contents, ...restOptions } = options;
1911
1979
  body = { query, ...restOptions };
@@ -1917,11 +1985,7 @@ var Exa2 = class {
1917
1985
  findSimilar(url, options) {
1918
1986
  let body;
1919
1987
  if (options === void 0 || !("contents" in options)) {
1920
- body = {
1921
- url,
1922
- ...options,
1923
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
1924
- };
1988
+ body = { url, ...options, contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } } };
1925
1989
  } else if (options.contents === false || options.contents === null || options.contents === void 0) {
1926
1990
  const { contents, ...restOptions } = options;
1927
1991
  body = { url, ...restOptions };
@@ -1934,14 +1998,43 @@ var Exa2 = class {
1934
1998
  return this.request("/contents", "POST", { urls, ...options });
1935
1999
  }
1936
2000
  answer(query, options) {
1937
- return this.request("/answer", "POST", { query, ...options });
2001
+ if (options?.stream) {
2002
+ throw new ExaError2("For streaming responses, please use streamAnswer() instead:\n\nfor await (const chunk of exa.streamAnswer(query)) {\n // Handle chunks\n}", 400);
2003
+ }
2004
+ return this.request("/answer", "POST", { query, model: "exa", stream: false, text: false, ...options });
1938
2005
  }
1939
- streamAnswer(query, options) {
1940
- return this.rawRequest("/answer", "POST", {
1941
- query,
1942
- stream: true,
1943
- ...options
1944
- });
2006
+ async *streamAnswer(query, options) {
2007
+ const response = await this.rawRequest("/answer", "POST", { query, model: "exa", text: false, ...options, stream: true });
2008
+ if (!response.ok) {
2009
+ throw await this.toExaError(response, "/answer");
2010
+ }
2011
+ const reader = response.body?.getReader();
2012
+ if (!reader) {
2013
+ throw new ExaError2("No response body available for streaming.", 500, (/* @__PURE__ */ new Date()).toISOString(), "/answer");
2014
+ }
2015
+ const decoder = new TextDecoder();
2016
+ let buffer = "";
2017
+ try {
2018
+ while (true) {
2019
+ const { done, value } = await reader.read();
2020
+ if (done) break;
2021
+ buffer += decoder.decode(value, { stream: true });
2022
+ const lines = buffer.split("\n");
2023
+ buffer = lines.pop() ?? "";
2024
+ for (const line of lines) {
2025
+ const chunk = this.parseAnswerStreamLine(line);
2026
+ if (chunk != null) {
2027
+ yield chunk;
2028
+ }
2029
+ }
2030
+ }
2031
+ const trailingChunk = this.parseAnswerStreamLine(buffer);
2032
+ if (trailingChunk != null) {
2033
+ yield trailingChunk;
2034
+ }
2035
+ } finally {
2036
+ reader.releaseLock();
2037
+ }
1945
2038
  }
1946
2039
  /**
1947
2040
  * @deprecated Use `search()` instead. The search method now returns text contents by default.
@@ -1955,11 +2048,7 @@ var Exa2 = class {
1955
2048
  });
1956
2049
  }
1957
2050
  const { contentsOptions, restOptions } = this.extractContentsOptions(options);
1958
- return this.request("/search", "POST", {
1959
- query,
1960
- contents: contentsOptions,
1961
- ...restOptions
1962
- });
2051
+ return this.request("/search", "POST", { query, contents: contentsOptions, ...restOptions });
1963
2052
  }
1964
2053
  /**
1965
2054
  * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
@@ -1973,11 +2062,7 @@ var Exa2 = class {
1973
2062
  });
1974
2063
  }
1975
2064
  const { contentsOptions, restOptions } = this.extractContentsOptions(options);
1976
- return this.request("/findSimilar", "POST", {
1977
- url,
1978
- contents: contentsOptions,
1979
- ...restOptions
1980
- });
2065
+ return this.request("/findSimilar", "POST", { url, contents: contentsOptions, ...restOptions });
1981
2066
  }
1982
2067
  };
1983
2068