exa-js 2.18.1 → 2.19.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.mjs CHANGED
@@ -4,7 +4,7 @@ import fetch2, { Headers } from "cross-fetch";
4
4
  // package.json
5
5
  var package_default = {
6
6
  name: "exa-js",
7
- version: "2.18.1",
7
+ version: "2.19.0",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -45,6 +45,7 @@ var package_default = {
45
45
  },
46
46
  license: "MIT",
47
47
  devDependencies: {
48
+ "@anthropic-ai/sdk": "^0.115.0",
48
49
  "@types/node": "~22.14.0",
49
50
  "cross-env": "~7.0.3",
50
51
  "openapi-typescript": "~7.6.1",
@@ -476,6 +477,10 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
476
477
  }
477
478
  };
478
479
 
480
+ // src/agent/types.ts
481
+ var AGENT_BETA_HEADER = "agent-2026-05-07";
482
+ var AGENT_MAX_EFFORT_BETA = "agent-max-effort-2026-07-27";
483
+
479
484
  // src/agent/client.ts
480
485
  var DEFAULT_AGENT_POLL_INTERVAL_MS = 1e3;
481
486
  var DEFAULT_AGENT_POLL_TIMEOUT_MS = 60 * 60 * 1e3;
@@ -817,6 +822,19 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
817
822
  headersForBetas(options?.betas)
818
823
  );
819
824
  }
825
+ /**
826
+ * Stop a running Agent run, completing it early with the results
827
+ * gathered so far. Only supported for `max` effort runs.
828
+ */
829
+ async stop(runId, options) {
830
+ return this.request(
831
+ `/${runId}/stop`,
832
+ "POST",
833
+ void 0,
834
+ void 0,
835
+ headersForBetas(options?.betas ?? [AGENT_MAX_EFFORT_BETA])
836
+ );
837
+ }
820
838
  async delete(runId, options) {
821
839
  return this.request(
822
840
  `/${runId}`,
@@ -2300,9 +2318,355 @@ var WebsetsClient = class extends WebsetsBaseClient {
2300
2318
  }
2301
2319
  };
2302
2320
 
2303
- // src/agent/types.ts
2304
- var AGENT_BETA_HEADER = "agent-2026-05-07";
2305
- var AGENT_MAX_EFFORT_BETA = "agent-max-effort-2026-07-27";
2321
+ // src/tools/core.ts
2322
+ import { z } from "zod";
2323
+ var DEFAULT_WEB_SEARCH_TOOL_DESCRIPTION = "Search the web for up-to-date, relevant information. Describe the ideal page rather than listing keywords.";
2324
+ function formatSearchResponse(response) {
2325
+ const formatted = response.results.map((result) => {
2326
+ const lines = [
2327
+ `Title: ${result.title || "N/A"}`,
2328
+ `URL: ${result.url || "N/A"}`,
2329
+ `Published: ${result.publishedDate || "N/A"}`,
2330
+ `Author: ${result.author || "N/A"}`
2331
+ ];
2332
+ if (result.highlights && result.highlights.length > 0) {
2333
+ lines.push(`Highlights:
2334
+ ${result.highlights.join("\n")}`);
2335
+ } else if (result.text) {
2336
+ lines.push(`Text: ${result.text}`);
2337
+ }
2338
+ return lines.join("\n");
2339
+ }).join("\n\n---\n\n");
2340
+ return formatted || "No search results found.";
2341
+ }
2342
+ function registerTool(registry, tool) {
2343
+ registry.register(tool);
2344
+ return tool;
2345
+ }
2346
+ function createTool(registry, params) {
2347
+ const tool = {
2348
+ name: params.name,
2349
+ description: params.description,
2350
+ inputSchema: params.inputSchema,
2351
+ jsonSchema: params.jsonSchema,
2352
+ execute: params.execute,
2353
+ format: params.format,
2354
+ definition: params.definition,
2355
+ async run(args) {
2356
+ try {
2357
+ const parsed = params.inputSchema.parse(args);
2358
+ const result = await params.execute(parsed);
2359
+ return params.format(result);
2360
+ } catch (error) {
2361
+ const message = error instanceof Error ? error.message : String(error);
2362
+ return `Error: ${message}`;
2363
+ }
2364
+ }
2365
+ };
2366
+ return registerTool(registry, tool);
2367
+ }
2368
+ function createWebSearchTool(exa, registry, config = {}) {
2369
+ const {
2370
+ name = "web_search",
2371
+ description = DEFAULT_WEB_SEARCH_TOOL_DESCRIPTION,
2372
+ ...searchOptions
2373
+ } = config;
2374
+ const inputSchema = z.object({
2375
+ query: z.string().describe(
2376
+ "Natural language search query. Should be a semantically rich description of the ideal page, not just keywords."
2377
+ )
2378
+ });
2379
+ const jsonSchema = zodToJsonSchema(inputSchema);
2380
+ delete jsonSchema.$schema;
2381
+ return createTool(registry, {
2382
+ name,
2383
+ description,
2384
+ inputSchema,
2385
+ jsonSchema,
2386
+ definition: {
2387
+ name,
2388
+ description,
2389
+ parameters: jsonSchema
2390
+ },
2391
+ execute: ({ query }) => {
2392
+ const options = {
2393
+ type: "auto",
2394
+ numResults: 10,
2395
+ contents: { highlights: true },
2396
+ ...searchOptions
2397
+ };
2398
+ return exa.search(query, options);
2399
+ },
2400
+ format: formatSearchResponse
2401
+ });
2402
+ }
2403
+ var ToolRegistry = class {
2404
+ constructor() {
2405
+ this.registry = /* @__PURE__ */ new Map();
2406
+ }
2407
+ register(tool) {
2408
+ this.registry.set(tool.name, tool);
2409
+ }
2410
+ resolve(tools) {
2411
+ return tools ? new Map(tools.map((tool) => [tool.name, tool])) : new Map(this.registry);
2412
+ }
2413
+ };
2414
+ function getTool(tools, name) {
2415
+ return tools.get(name);
2416
+ }
2417
+ function unknownToolError(name) {
2418
+ return `Error: unknown tool "${name}"`;
2419
+ }
2420
+
2421
+ // src/tools/anthropic.ts
2422
+ var AnthropicTools = class {
2423
+ constructor(exa, registry) {
2424
+ this.exa = exa;
2425
+ this.registry = registry;
2426
+ }
2427
+ /** Anthropic `web_search` tool. Defaults to `auto` + highlights. */
2428
+ webSearch(config) {
2429
+ return runnable(createWebSearchTool(this.exa, this.registry, config));
2430
+ }
2431
+ /**
2432
+ * Run the `tool_use` blocks in an assistant message and return the matching
2433
+ * `tool_result` blocks. Every `tool_use` block is answered so the follow-up
2434
+ * request never omits a required result: a block whose name doesn't match a
2435
+ * known tool gets an `Error: unknown tool "<name>"` result. When handling
2436
+ * some tools yourself, replace those error results with your own before
2437
+ * sending the next request.
2438
+ */
2439
+ async handleToolUse(message, options) {
2440
+ const tools = this.registry.resolve(options?.tools);
2441
+ const blocks = (message.content ?? []).filter(isAnthropicToolUse);
2442
+ return Promise.all(
2443
+ blocks.map(async (block) => {
2444
+ const tool = getTool(tools, block.name);
2445
+ return {
2446
+ type: "tool_result",
2447
+ tool_use_id: block.id,
2448
+ content: tool ? await tool.run(block.input) : unknownToolError(block.name)
2449
+ };
2450
+ })
2451
+ );
2452
+ }
2453
+ };
2454
+ function isAnthropicToolUse(value) {
2455
+ if (!value || typeof value !== "object") return false;
2456
+ const block = value;
2457
+ return block.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string";
2458
+ }
2459
+ function runnable(tool) {
2460
+ const definition = {
2461
+ type: "custom",
2462
+ name: tool.name,
2463
+ description: tool.description,
2464
+ input_schema: tool.jsonSchema,
2465
+ parse: (input) => tool.inputSchema.parse(input),
2466
+ run: (args) => tool.run(args)
2467
+ };
2468
+ Object.defineProperties(definition, {
2469
+ parse: { enumerable: false },
2470
+ run: { enumerable: false }
2471
+ });
2472
+ Object.defineProperties(
2473
+ definition,
2474
+ Object.fromEntries(
2475
+ Object.entries(tool).filter(([key]) => !["name", "description"].includes(key)).map(([key, value]) => [
2476
+ key,
2477
+ { value, enumerable: false, configurable: true }
2478
+ ])
2479
+ )
2480
+ );
2481
+ Object.defineProperty(definition, "type", {
2482
+ value: "custom",
2483
+ enumerable: false,
2484
+ configurable: true
2485
+ });
2486
+ Object.defineProperty(definition, "definition", {
2487
+ value: {
2488
+ name: tool.name,
2489
+ description: tool.description,
2490
+ input_schema: tool.jsonSchema
2491
+ },
2492
+ enumerable: false
2493
+ });
2494
+ return definition;
2495
+ }
2496
+
2497
+ // src/tools/openai.ts
2498
+ function runnable2(tool) {
2499
+ const functionDefinition = {
2500
+ ...tool.definition,
2501
+ parse: (input) => JSON.parse(input),
2502
+ function: (args) => tool.run(args)
2503
+ };
2504
+ Object.defineProperties(functionDefinition, {
2505
+ parse: { enumerable: false },
2506
+ function: { enumerable: false }
2507
+ });
2508
+ const definition = {
2509
+ type: "function",
2510
+ function: functionDefinition
2511
+ };
2512
+ Object.defineProperties(
2513
+ definition,
2514
+ Object.fromEntries(
2515
+ Object.entries(tool).filter(([key]) => !["name", "description"].includes(key)).map(([key, value]) => [
2516
+ key,
2517
+ { value, enumerable: false, configurable: true }
2518
+ ])
2519
+ )
2520
+ );
2521
+ Object.defineProperties(definition, {
2522
+ name: {
2523
+ value: tool.name,
2524
+ enumerable: false,
2525
+ configurable: true
2526
+ },
2527
+ description: {
2528
+ value: tool.description,
2529
+ enumerable: false,
2530
+ configurable: true
2531
+ }
2532
+ });
2533
+ Object.defineProperty(definition, "definition", {
2534
+ value: {
2535
+ type: "function",
2536
+ function: {
2537
+ name: tool.name,
2538
+ description: tool.description,
2539
+ parameters: tool.jsonSchema
2540
+ }
2541
+ },
2542
+ enumerable: false,
2543
+ configurable: true
2544
+ });
2545
+ return definition;
2546
+ }
2547
+ var OpenAIResponsesTools = class {
2548
+ constructor(exa, registry, handleResponses) {
2549
+ this.exa = exa;
2550
+ this.registry = registry;
2551
+ this.handleResponses = handleResponses;
2552
+ }
2553
+ /** Responses API `web_search` tool. Defaults to `auto` + highlights. */
2554
+ webSearch(config) {
2555
+ return responsesRunnable(
2556
+ createWebSearchTool(this.exa, this.registry, config)
2557
+ );
2558
+ }
2559
+ /**
2560
+ * Run the function calls in a Responses API response (or output item array)
2561
+ * and return `function_call_output` items. Every function call is answered
2562
+ * so the follow-up request never omits a required output: a call whose name
2563
+ * doesn't match a known tool gets an `Error: unknown tool "<name>"` output.
2564
+ * When handling some tools yourself, replace those error outputs with your
2565
+ * own results before sending the next request.
2566
+ */
2567
+ async handleToolCalls(responseOrOutputItems, options) {
2568
+ return this.handleResponses(responseOrOutputItems, options);
2569
+ }
2570
+ };
2571
+ function responsesRunnable(tool) {
2572
+ const definition = {
2573
+ type: "function",
2574
+ name: tool.name,
2575
+ description: tool.description,
2576
+ parameters: tool.jsonSchema,
2577
+ strict: false
2578
+ };
2579
+ Object.defineProperties(
2580
+ definition,
2581
+ Object.fromEntries(
2582
+ Object.entries(tool).filter(([key]) => !["name", "description"].includes(key)).map(([key, value]) => [
2583
+ key,
2584
+ { value, enumerable: false, configurable: true }
2585
+ ])
2586
+ )
2587
+ );
2588
+ Object.defineProperty(definition, "definition", {
2589
+ value: {
2590
+ ...tool.definition,
2591
+ type: "function",
2592
+ parameters: tool.jsonSchema,
2593
+ strict: false
2594
+ },
2595
+ enumerable: false
2596
+ });
2597
+ return definition;
2598
+ }
2599
+ var OpenAITools = class {
2600
+ constructor(exa, registry) {
2601
+ this.exa = exa;
2602
+ this.registry = registry;
2603
+ this.responses = new OpenAIResponsesTools(
2604
+ exa,
2605
+ registry,
2606
+ (responseOrOutputItems, options) => this.handleResponsesToolCalls(responseOrOutputItems, options)
2607
+ );
2608
+ }
2609
+ /** Chat Completions `web_search` tool. Defaults to `auto` + highlights. */
2610
+ webSearch(config) {
2611
+ return runnable2(createWebSearchTool(this.exa, this.registry, config));
2612
+ }
2613
+ async handleToolCalls(assistantMessage, options) {
2614
+ if (isResponsesInput(assistantMessage)) {
2615
+ return this.handleResponsesToolCalls(assistantMessage, options);
2616
+ }
2617
+ return this.handleChatToolCalls(assistantMessage, options);
2618
+ }
2619
+ async handleChatToolCalls(assistantMessage, options) {
2620
+ const tools = this.registry.resolve(options?.tools);
2621
+ const calls = (assistantMessage.tool_calls ?? []).filter(isOpenAIToolCall);
2622
+ return Promise.all(
2623
+ calls.map(async (call) => {
2624
+ const tool = getTool(tools, call.function.name);
2625
+ return {
2626
+ role: "tool",
2627
+ tool_call_id: call.id,
2628
+ content: tool ? await tool.run(parseArguments(call.function.arguments)) : unknownToolError(call.function.name)
2629
+ };
2630
+ })
2631
+ );
2632
+ }
2633
+ async handleResponsesToolCalls(responseOrOutputItems, options) {
2634
+ const tools = this.registry.resolve(options?.tools);
2635
+ const rawItems = !Array.isArray(responseOrOutputItems) && "output" in responseOrOutputItems ? responseOrOutputItems.output ?? [] : responseOrOutputItems;
2636
+ const items = rawItems.filter(isResponsesFunctionCall);
2637
+ return Promise.all(
2638
+ items.map(async (call) => {
2639
+ const tool = getTool(tools, call.name);
2640
+ return {
2641
+ type: "function_call_output",
2642
+ call_id: call.call_id,
2643
+ output: tool ? await tool.run(parseArguments(call.arguments)) : unknownToolError(call.name)
2644
+ };
2645
+ })
2646
+ );
2647
+ }
2648
+ };
2649
+ function parseArguments(argumentsText) {
2650
+ try {
2651
+ return JSON.parse(argumentsText);
2652
+ } catch {
2653
+ return argumentsText;
2654
+ }
2655
+ }
2656
+ function isOpenAIToolCall(value) {
2657
+ if (!value || typeof value !== "object") return false;
2658
+ const call = value;
2659
+ return typeof call.id === "string" && !!call.function && typeof call.function.name === "string" && typeof call.function.arguments === "string";
2660
+ }
2661
+ function isResponsesFunctionCall(value) {
2662
+ if (!value || typeof value !== "object") return false;
2663
+ const call = value;
2664
+ return call.type === "function_call" && typeof call.call_id === "string" && typeof call.name === "string" && typeof call.arguments === "string";
2665
+ }
2666
+ function isResponsesInput(value) {
2667
+ if (Array.isArray(value)) return value.some(isResponsesFunctionCall);
2668
+ return "output" in value;
2669
+ }
2306
2670
 
2307
2671
  // src/index.ts
2308
2672
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : fetch2;
@@ -2325,6 +2689,39 @@ function truncateResponseBody(text) {
2325
2689
  return collapsed.length > NON_JSON_BODY_SNIPPET_LENGTH ? `${collapsed.slice(0, NON_JSON_BODY_SNIPPET_LENGTH)}\u2026` : collapsed;
2326
2690
  }
2327
2691
  var Exa2 = class {
2692
+ /**
2693
+ * Constructs the Exa API client.
2694
+ * @param {string} apiKey - The API key for authentication.
2695
+ * @param {string} [baseURL] - The base URL of the Exa API.
2696
+ */
2697
+ constructor(apiKey, baseURL = "https://api.exa.ai") {
2698
+ this.toolRegistry = new ToolRegistry();
2699
+ this.baseURL = baseURL;
2700
+ if (!apiKey) {
2701
+ apiKey = process.env.EXA_API_KEY;
2702
+ if (!apiKey) {
2703
+ throw new ExaError(
2704
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
2705
+ 401 /* Unauthorized */
2706
+ );
2707
+ }
2708
+ }
2709
+ this.headers = new HeadersImpl({
2710
+ "x-api-key": apiKey,
2711
+ "Content-Type": "application/json",
2712
+ "User-Agent": `exa-node ${package_default.version}`
2713
+ });
2714
+ this.websets = new WebsetsClient(this);
2715
+ this.research = new ResearchClient(this);
2716
+ this.monitors = new SearchMonitorsClient(this);
2717
+ this.agent = new AgentClient(this);
2718
+ this.beta = new BetaClient(this.agent);
2719
+ this.tools = {
2720
+ webSearch: (options) => createWebSearchTool(this, this.toolRegistry, options)
2721
+ };
2722
+ this.openai = new OpenAITools(this, this.toolRegistry);
2723
+ this.anthropic = new AnthropicTools(this, this.toolRegistry);
2724
+ }
2328
2725
  /**
2329
2726
  * Helper method to separate out the contents-specific options from the rest.
2330
2727
  */
@@ -2389,33 +2786,6 @@ var Exa2 = class {
2389
2786
  }
2390
2787
  return { query, ...requestOptions };
2391
2788
  }
2392
- /**
2393
- * Constructs the Exa API client.
2394
- * @param {string} apiKey - The API key for authentication.
2395
- * @param {string} [baseURL] - The base URL of the Exa API.
2396
- */
2397
- constructor(apiKey, baseURL = "https://api.exa.ai") {
2398
- this.baseURL = baseURL;
2399
- if (!apiKey) {
2400
- apiKey = process.env.EXA_API_KEY;
2401
- if (!apiKey) {
2402
- throw new ExaError(
2403
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
2404
- 401 /* Unauthorized */
2405
- );
2406
- }
2407
- }
2408
- this.headers = new HeadersImpl({
2409
- "x-api-key": apiKey,
2410
- "Content-Type": "application/json",
2411
- "User-Agent": `exa-node ${package_default.version}`
2412
- });
2413
- this.websets = new WebsetsClient(this);
2414
- this.research = new ResearchClient(this);
2415
- this.monitors = new SearchMonitorsClient(this);
2416
- this.agent = new AgentClient(this);
2417
- this.beta = new BetaClient(this.agent);
2418
- }
2419
2789
  /**
2420
2790
  * Makes a request to the Exa API.
2421
2791
  * @param {string} endpoint - The API endpoint to call.
@@ -2875,9 +3245,11 @@ export {
2875
3245
  AgentRunEventsClient,
2876
3246
  AgentRunFailedError,
2877
3247
  AgentRunsClient,
3248
+ AnthropicTools,
2878
3249
  BetaClient,
2879
3250
  CreateEnrichmentParametersFormat,
2880
3251
  CreateImportParametersFormat,
3252
+ DEFAULT_WEB_SEARCH_TOOL_DESCRIPTION,
2881
3253
  EventType,
2882
3254
  EventsClient,
2883
3255
  Exa2 as Exa,
@@ -2893,8 +3265,11 @@ export {
2893
3265
  MonitorRunStatus,
2894
3266
  MonitorRunType,
2895
3267
  MonitorStatus,
3268
+ OpenAIResponsesTools,
3269
+ OpenAITools,
2896
3270
  SearchMonitorRunsClient,
2897
3271
  SearchMonitorsClient,
3272
+ ToolRegistry,
2898
3273
  UpdateMonitorStatus,
2899
3274
  WebhookStatus,
2900
3275
  WebsetEnrichmentFormat,
@@ -2914,6 +3289,7 @@ export {
2914
3289
  WebsetStatus,
2915
3290
  WebsetWebhooksClient,
2916
3291
  WebsetsClient,
3292
+ createWebSearchTool,
2917
3293
  index_default as default
2918
3294
  };
2919
3295
  //# sourceMappingURL=index.mjs.map