Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Tavily JS
https://github.com/tavily-ai/tavily-js
Admin
Official TypeScript/JavaScript library for Tavily.
Tokens:
61,302
Snippets:
312
Trust Score:
8.7
License:
MIT
Update:
1 week ago
Context
Chat
Benchmark
89.19
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Install @tavily/core with npm Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Install the Tavily JavaScript SDK package using npm. Run this command in your project directory. ```bash npm i @tavily/core ``` -------------------------------- ### client.crawl() Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/crawl.md Agent-first site crawler: breadth-first navigation from a start URL, guided by a natural-language goal. Requires an API key (throws on a keyless client). Imported via the factory: const { crawl } = tavily(...). ```APIDOC ## client.crawl() ### Description Agent-first site crawler: breadth-first navigation from a start URL, guided by a natural-language goal. Requires an API key (throws on a keyless client). Imported via the factory: `const { crawl } = tavily(...)`. ### Signature ```ts export type TavilyCrawlFunction = ( url: string, options?: TavilyCrawlOptions ) => Promise<TavilyCrawlResponse>; ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `url` | `string` | yes | — | Start URL. Sent as body field `url`. | | `options` | `Partial<TavilyCrawlOptions>` | no | `{}` | See below. Extra keys forwarded verbatim via `...kwargs`. | ### TavilyCrawlOptions ```ts export type TavilyCrawlOptions = { maxDepth?: number; maxBreadth?: number; limit?: number; instructions?: string; extractDepth?: "basic" | "advanced"; selectPaths?: string[]; selectDomains?: string[]; excludePaths?: string[]; excludeDomains?: string[]; allowExternal?: boolean; includeImages?: boolean; format?: "markdown" | "text"; timeout?: number; includeFavicon?: boolean; includeUsage?: boolean; chunksPerSource?: number; sessionId?: string; humanId?: string; clientName?: string; [key: string]: any; }; ``` | Option | Type | Server field | Notes | |--------|------|--------------|-------| | `maxDepth` | `number` | `max_depth` | — | | `maxBreadth` | `number` | `max_breadth` | — | | `limit` | `number` | `limit` | max pages to return | | `instructions` | `string` | `instructions` | natural-language goal steering the crawl | | `extractDepth` | `"basic" \| "advanced"` | `extract_depth` | — | | `selectPaths` | `string[]` | `select_paths` | URL paths to include | | `selectDomains` | `string[]` | `select_domains` | — | | `excludePaths` | `string[]` | `exclude_paths` | — | | `excludeDomains` | `string[]` | `exclude_domains` | — | | `allowExternal` | `boolean` | `allow_external` | allow leaving the base domain | | `includeImages` | `boolean` | `include_images` | populates `result.images` | | `format` | `"markdown" \| "text"` | `format` | output format | | `timeout` | `number` | `timeout` (body) + axios timeout | default 150 s | | `includeFavicon` | `boolean` | `include_favicon` | — | | `includeUsage` | `boolean` | `include_usage` | populates `response.usage` | | `chunksPerSource` | `number` | `chunks_per_source` | — | | `sessionId`/`humanId`/`clientName` | `string` | headers | per-call override (merged only when defined) | ### Return Value Returns a `Promise<TavilyCrawlResponse>`. ### Notes - Requires an API key; throws on a keyless client. - Extra keys in `options` are forwarded verbatim via `...kwargs`. - `sessionId`, `humanId`, and `clientName` are sent as headers and merged only when defined. ``` -------------------------------- ### Usage example for client.searchContext Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/legacy-search.md Deprecated usage example. Creates a Tavily client with an API key, calls `searchContext` with a query and options, parses the returned JSON string, and logs the number of sources. Emits a deprecation warning on each invocation. ```typescript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Deprecated — prefer search() and build context yourself const contextJson = await tvly.searchContext("Tavily SDK", { maxTokens: 2000, maxResults: 10, }); const context = JSON.parse(contextJson); // [{ url, content }, ...] console.log(context.length, "sources fit within the token budget"); ``` -------------------------------- ### Basic Tavily Search Example Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Instantiate the Tavily client with your API key and execute a simple search query. The response is logged to the console. ```javascript const { tavily } = require("@tavily/core"); // Step 1. Instantiating your Tavily client const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Step 2. Executing a simple search query const response = await tvly.search("Who is Leo Messi?"); // Step 3. That's it! You've done a Tavily Search! console.log(response); ``` -------------------------------- ### Basic map with instructions Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/map.md Example usage of tvly.map() with maxDepth, limit, and instructions options. Requires an API key. ```TypeScript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); const response = await tvly.map("https://wikipedia.org/wiki/Lemon", { maxDepth: 3, limit: 50, instructions: "Find all pages on citrus fruits", }); for (const url of response.results) { console.log(`URL: ${url}`); } ``` -------------------------------- ### Example output of searchContext Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/legacy-search.md Example JSON output returned by `searchContext`. It is an array of objects with `url` and `content` fields. ```json [{"url":"https://en.wikipedia.org/wiki/...","content":"..."}] ``` -------------------------------- ### Map a website with Tavily Map Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Use the tavily.map method to discover and visualize the structure of a website starting from a base URL. Requires an API key. The example sets max_depth to 3, limit to 50, and instructions to focus on citrus fruit pages. Results are printed as URLs. ```javascript const { tavily } = require("@tavily/core"); // Step 1. Instantiating your Tavily client const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Step 2. Defining the starting URL const start_url = "https://wikipedia.org/wiki/Lemon"; // Step 3. Executing the map request with parameters to focus on specific pages response = await tvly.map(start_url, { max_depth: 3, limit: 50, instructions: "Find all pages on citrus fruits", }); // Step 4. Printing the site structure for (let url of response.results) { console.log(`URl: ${url}`); } ``` -------------------------------- ### searchQNA usage example (deprecated) Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/legacy-search.md Example of using the deprecated searchQNA method. Prefer tvly.search(q, { includeAnswer: true }) instead. ```typescript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Deprecated — prefer: const { answer } = await tvly.search(q, { includeAnswer: true }); const answer = await tvly.searchQNA("What is the capital of France?", { searchDepth: "advanced", maxResults: 5, }); console.log(answer); ``` -------------------------------- ### Structured output and streaming Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/research.md Shows two research calls: one with an outputSchema for structured report shape, and one with stream: true that yields raw Buffer chunks. The streaming example accumulates chunks as UTF-8 strings. ```ts import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Structured report shape await tvly.research("AI market overview", { model: "auto", outputSchema: { summary: { type: "string" }, companies: { type: "array", items: { type: "string" } }, }, }); // Streaming: yields raw Buffer chunks of the streamed response const stream = await tvly.research("Latest developments in AI", { model: "pro", stream: true, }); let text = ""; for await (const chunk of stream) { text += chunk.toString("utf-8"); } console.log(text); ``` -------------------------------- ### POST /crawl Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/endpoints.md Crawls a website starting from a given URL. Called by the crawl() method. ```APIDOC ## POST /crawl ### Description Crawls a website starting from a given URL. Called by the `crawl()` method. ### Method POST ### Endpoint /crawl ### Parameters #### Request Body - **url** (string) - Required - Start URL for crawling. - **max_depth** (number) - Optional - Maximum crawl depth. - **max_breadth** (number) - Optional - Maximum crawl breadth. - **limit** (number) - Optional - Maximum number of pages to crawl. - **extract_depth** ("basic" | "advanced") - Optional - Extraction depth. - **select_paths** (string[]) - Optional - Paths to include. - **select_domains** (string[]) - Optional - Domains to include. - **exclude_paths** (string[]) - Optional - Paths to exclude. - **exclude_domains** (string[]) - Optional - Domains to exclude. - **allow_external** (boolean) - Optional - Whether to allow external links. - **include_images** (boolean) - Optional - Whether to include images. - **instructions** (string) - Optional - Natural-language goal. - **format** ("markdown" | "text") - Optional - Output format. - **timeout** (number) - Optional - Timeout in seconds (client default 150s). - **include_favicon** (boolean) - Optional - Whether to include favicon. - **include_usage** (boolean) - Optional - Whether to include usage. - **chunks_per_source** (number) - Optional - Number of chunks per source. - **...kwargs** (any) - Optional - Extra keys forwarded. ### Response #### Success Response (200) - **responseTime** (number) - Response time. - **baseUrl** (string) - Base URL of the crawl. - **results** (Array<{url: string, raw_content: string, images: any, favicon?: any}>) - Crawl results. - **requestId** (string) - Request ID. - **usage** (any) - Usage information. ``` -------------------------------- ### POST /map Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/endpoints.md Maps a starting URL to discover related links. Called by the map() method. ```APIDOC ## POST /map ### Description Maps a starting URL to discover related links. Called by the map() method. ### Method POST ### Endpoint /map ### Parameters #### Request Body - **url** (string) - Required - Start URL - **max_depth** (number) - Optional - Maximum depth to crawl - **max_breadth** (number) - Optional - Maximum breadth to crawl - **limit** (number) - Optional - Limit on number of results - **select_paths** (string[]) - Optional - Paths to include - **select_domains** (string[]) - Optional - Domains to include - **exclude_paths** (string[]) - Optional - Paths to exclude - **exclude_domains** (string[]) - Optional - Domains to exclude - **allow_external** (boolean) - Optional - Whether to allow external links - **instructions** (string) - Optional - Additional instructions - **timeout** (number) - Optional - Timeout in seconds; also used as axios timeout; client default 150s - **include_usage** (boolean) - Optional - Whether to include usage information - **...kwargs** (any) - Optional - Extra keys forwarded ### Response #### Success Response (200) - **responseTime** (number) - Response time in milliseconds - **baseUrl** (string) - Base URL of the mapped site - **results** (string[]) - List of discovered URLs - **requestId** (string) - Request identifier - **usage** (object) - Optional usage information #### Response Example { "responseTime": 123, "baseUrl": "https://example.com", "results": ["https://example.com/page1", "https://example.com/page2"], "requestId": "abc123" } ``` -------------------------------- ### map(url, options?) Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/map.md Discovers and returns the structure (list of URLs) of a website starting from a base URL. Requires an API key (throws on a keyless client). Imported via the factory: `const { map } = tavily(...)`. ```APIDOC ## map(url, options?) ### Description Discovers and returns the structure (list of URLs) of a website starting from a base URL. Requires an API key (throws on a keyless client). Imported via the factory: `const { map } = tavily(...)`. ### Signature ```ts export type TavilyMapFunction = ( url: string, options?: TavilyMapOptions ) => Promise<TavilyMapResponse>; ``` ### Parameters #### Path Parameters - **url** (string) - Required - Start URL. Sent as body field `url`. #### Request Body - **options** (Partial<TavilyMapOptions>) - Optional - See below. Extra keys forwarded verbatim via `...kwargs`. ### TavilyMapOptions | Option | Type | Server field | Notes | |--------|------|--------------|-------| | `limit` | `number` | `limit` | max URLs to return | | `maxDepth` | `number` | `max_depth` | — | | `maxBreadth` | `number` | `max_breadth` | — | | `selectPaths` | `string[]` | `select_paths` | — | | `selectDomains` | `string[]` | `select_domains` | — | | `excludePaths` | `string[]` | `exclude_paths` | — | | `excludeDomains` | `string[]` | `exclude_domains` | — | | `allowExternal` | `boolean` | `allow_external` | — | | `instructions` | `string` | `instructions` | natural-language focus for the map | | `timeout` | `number` | `timeout` (body) + axios timeout | default 150 s | | `includeUsage` | `boolean` | `include_usage` | populates `response.usage` | | `sessionId`/`humanId`/`clientName` | `string` | headers | per-call override (merged only when defined) | ### Return type `Promise<TavilyMapResponse>`: ```ts export type TavilyMapResponse = { responseTime: number; baseUrl: string; results: string[]; usage?: { credits: number }; requestId: string; }; ``` ### Response #### Success Response - **responseTime** (number) - Response time in milliseconds. - **baseUrl** (string) - The base URL of the mapped site. - **results** (string[]) - Array of URL strings. - **usage** (object, optional) - Usage information with `credits` (number). - **requestId** (string) - Unique request identifier. ### Throws / rejects | Error | Condition | |-------|-----------| | `Error` | Keyless client — thrown synchronously: `` `map: Keyless mode only supports search and extract; provide an API key to use this method.` `` | | `Error` | `Request timed out after ${timeout} seconds.` on axios `ECONNABORTED` (default 150 s) | | `Error` / `TavilyKeylessLimitError` | API error response via `handleRequestError` | | `Error` | Wrapper: `An unexpected error occurred while making the request. Error: ${err}` | ### Usage examples #### Basic map with instructions ```ts import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); const response = await tvly.map("https://wikipedia.org/wiki/Lemon", { maxDepth: 3, limit: 50, instructions: "Find all pages on citrus fruits", }); for (const url of response.results) { console.log(`URL: ${url}`); } ``` #### Scoped map with error handling ```ts import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); try { const response = await tvly.map("https://example.com", { maxDepth: 2, maxBreadth: 10, selectPaths: ["/docs"], excludePaths: ["/admin"], allowExternal: false, includeUsage: true, }); console.log(`Mapped ${response.results.length} URLs under ${response.baseUrl}`); console.log("usage:", response.usage?.credits, "requestId:", response.requestId); } catch (err) { if (err instanceof Error && /timed out/.test(err.message)) { console.log("increase map timeout — it defaults to 150s"); } else { throw err; } } ``` ``` -------------------------------- ### SDK Overview Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/README.md Provides quick facts about the SDK including base URL, timeouts, keyless mode, and option type behavior. ```APIDOC ## SDK Overview ### Base URL - Default: `https://api.tavily.com` - Override with `apiBaseURL`. ### Timeouts - `search`: 60 seconds - `extract`: 30 seconds - `crawl`: 150 seconds - `map`: 150 seconds - `getResearch`: 60 seconds - `feedback`: 10 seconds - `research`: no default (request only times out if a `timeout` is provided) ### Keyless Mode - If no `apiKey` and no `TAVILY_API_KEY` is set, only `search` and `extract` work. - All other methods throw immediately. ### Option Types - All search/extract/crawl/map/research/feedback option types include `[key: string]: any`. - Extra keys are forwarded verbatim to the API request body as kwargs. - `TavilyGetResearchOptions` is the exception: it has no index signature and maps to a query parameter. ``` -------------------------------- ### Crawl a website with Tavily Crawl Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Use the tavily.crawl method to perform a breadth-first crawl starting from a URL. Requires an API key. The example sets max_depth to 3, limit to 50, and instructions to find pages about citrus fruits. Results are printed with URL and first 200 characters of raw content. ```javascript const { tavily } = require("@tavily/core"); // Step 1. Instantiating your Tavily client const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Step 2. Defining the starting URL to crawl const start_url = "https://wikipedia.org/wiki/Lemon"; // Step 3. Executing the crawl request with instructions to surface only pages about citrus fruits response = await tvly.crawl(start_url, { max_depth: 3, limit: 50, instructions: "Find all pages on citrus fruits", }); // Step 4. Printing pages matching the query for (let result of response.results) { console.log(`URL: ${result.url}`); console.log(`Raw Content: ${result.rawContent.substring(0, 200)}...`); } ``` -------------------------------- ### Basic initialization and search Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/tavily.md Initializes the Tavily client with an API key and performs a search query. ```APIDOC ## tavily({ apiKey }) -> client ### Description Initializes the Tavily client with an API key. The client can then be used to perform search operations. ### Method Initialization (constructor) ### Parameters - **apiKey** (string) - Required - Your Tavily API key. ### Request Example ```ts import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); const response = await tvly.search("Who is Leo Messi?"); console.log(response); ``` ### Response Returns a client object with a `search` method that returns a search response. ``` -------------------------------- ### Basic initialization with tavily() Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/tavily.md Initializes the Tavily client with an API key and performs a search query. The response is logged to the console. ```TypeScript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); const response = await tvly.search("Who is Leo Messi?"); console.log(response); ``` -------------------------------- ### Initialize Tavily client with environment variables (TypeScript) Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/configuration.md Creates a Tavily client that reads configuration from environment variables (TAVILY_API_KEY, TAVILY_HTTPS_PROXY, TAVILY_PROJECT, TAVILY_ORG_ID) and performs a search. ```ts import { tavily } from "@tavily/core"; // Reads TAVILY_API_KEY, TAVILY_HTTPS_PROXY, TAVILY_PROJECT, TAVILY_ORG_ID const tvly = tavily(); const res = await tvly.search("NVIDIA earnings"); ``` -------------------------------- ### Keyless initialization and keyless-limit error handling Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/tavily.md Initializes the Tavily client without an API key (keyless mode) and demonstrates handling of the TavilyKeylessLimitError. Also notes that crawl is not supported in keyless mode. ```APIDOC ## tavily() -> client (keyless mode) ### Description Initializes the Tavily client without an API key, enabling keyless mode. In keyless mode, search and extract are supported, but crawl is not. If the keyless limit is reached, a `TavilyKeylessLimitError` is thrown. ### Method Initialization (constructor) ### Parameters None (no apiKey provided, and no TAVILY_API_KEY env var). ### Request Example ```ts import { tavily, TavilyKeylessLimitError } from "@tavily/core"; // No apiKey, no TAVILY_API_KEY env var → keyless mode const tvly = tavily(); try { const response = await tvly.search("Who is Leo Messi?"); console.log(response); } catch (err) { if (err instanceof TavilyKeylessLimitError) { console.log("cap:", err.capType); console.log("retry after:", err.retryAfter); console.log("bonus eligible:", err.bonusEligible); console.log("continuation options:", err.continuationPaths); } else { throw err; } } // These throw synchronously with Error("crawl: Keyless mode only supports search and extract; provide an API key to use this method.") await tvly.crawl("https://example.com"); // throws ``` ### Response Returns a client object. In keyless mode, `search` and `extract` are supported; `crawl` throws an error. If the keyless limit is reached, a `TavilyKeylessLimitError` is thrown with properties `capType`, `retryAfter`, `bonusEligible`, and `continuationPaths`. ``` -------------------------------- ### Scoped map with error handling Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/map.md Example usage of tvly.map() with scoping options (selectPaths, excludePaths, allowExternal) and includeUsage, wrapped in try/catch to handle timeout errors. ```TypeScript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); try { const response = await tvly.map("https://example.com", { maxDepth: 2, maxBreadth: 10, selectPaths: ["/docs"], excludePaths: ["/admin"], allowExternal: false, includeUsage: true, }); console.log(`Mapped ${response.results.length} URLs under ${response.baseUrl}`); console.log("usage:", response.usage?.credits, "requestId:", response.requestId); } catch (err) { if (err instanceof Error && /timed out/.test(err.message)) { console.log("increase map timeout — it defaults to 150s"); } else { throw err; } } ``` -------------------------------- ### Initialization with proxies, organization scoping, and session tracking Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/tavily.md Initializes the Tavily client with additional configuration options for proxies, organization/project scoping, session tracking, and client identification. ```APIDOC ## tavily({ apiKey, proxies, projectId, orgId, sessionId, humanId, clientName, clientSource }) -> client ### Description Initializes the Tavily client with advanced options for proxy support, organization/project scoping, session tracking, and client identification. ### Method Initialization (constructor) ### Parameters - **apiKey** (string) - Required - Your Tavily API key. - **proxies** (object) - Optional - Proxy configuration. Supports `http` and `https` properties. - **projectId** (string) - Optional - Project identifier for scoping. - **orgId** (string) - Optional - Organization identifier for scoping. - **sessionId** (string) - Optional - Session identifier for tracking. - **humanId** (string) - Optional - Internal user identifier. - **clientName** (string) - Optional - Name of the client application. - **clientSource** (string) - Optional - Source of the client. ### Request Example ```ts import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY", proxies: { http: "http://proxy.local:8080" }, // https also supported projectId: "proj_123", orgId: "org_456", sessionId: "my-session-123", humanId: "internal-user-id-42", clientName: "my-app", clientSource: "my-custom-client", }); ``` ### Response Returns a client object with the configured options. ``` -------------------------------- ### TavilyCrawlFunction type signature Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/crawl.md Exact type signature for the crawl function from src/types.ts:29. It takes a start URL and accepts optional TavilyCrawlOptions, returning a Promise of TavilyCrawlResponse. ```ts export type TavilyCrawlFunction = ( url: string, options?: TavilyCrawlOptions ) => Promise<TavilyCrawlResponse>; ``` -------------------------------- ### POST /search (searchQNA) Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/legacy-search.md Deprecated client method `searchQNA()` that maps to POST /search and returns only the answer string. It is deprecated and will be removed in a future version; use `search()` with `includeAnswer: true` instead. ```APIDOC ## [POST] /search ### Description Deprecated client method that performs a search and returns only the answer string. It maps to the `/search` endpoint with `includeAnswer` always set to `true`. This method is deprecated and will be removed in a future version; use `search()` with `includeAnswer: true` instead. ### Method POST ### Endpoint /search ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body - **query** (string) - Required - Search query. - **search_depth** (string) - Optional - Default: `"advanced"`. Search depth. - **topic** (string) - Optional - Topic filter. - **days** (number) - Optional - Number of days to search. - **max_results** (number) - Optional - Maximum number of results. - **include_answer** (boolean) - Always `true`. - **include_domains** (array of strings) - Optional - Domains to include. - **exclude_domains** (array of strings) - Optional - Domains to exclude. - **chunks_per_source** (number) - Optional - Chunks per source. - **include_favicon** (boolean) - Optional - Include favicon. ### Request Example ```json { "query": "What is the capital of France?", "search_depth": "advanced", "max_results": 5, "include_answer": true } ``` ### Response #### Success Response (200) - **answer** (string) - The answer string from the API. #### Response Example ```json { "answer": "Paris" } ``` ### Error Handling - **Error** - Keyless client: thrown synchronously with message `searchQNA: Keyless mode only supports search and extract; provide an API key to use this method.` - **Error** - Request timed out after 60 seconds (default) on axios `ECONNABORTED`. - **Error** / **TavilyKeylessLimitError** - API error response via `handleRequestError`. - **Error** - Wrapper: `An unexpected error occurred while making the request. Error: ${err}`. ``` -------------------------------- ### Check research credit usage Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Retrieves a research result with the 'includeUsage' option to get credit usage information. Usage is off by default and some tasks have no usage data. ```javascript const { tavily } = require("@tavily/core"); const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); const result = await tvly.getResearch("YOUR_REQUEST_ID", { includeUsage: true }); console.log(result.usage?.credits); ``` -------------------------------- ### Set session and user tracking at client init and per-call Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Shows how to set optional sessionId, humanId, and clientName at client initialization so they apply to every request, and how to override them per call. Per-call values take precedence. These identifiers are sent as HTTP headers and humanId is hashed server-side. ```javascript // Client-level — applied to every request const client = tavily({ apiKey: "tvly-YOUR_API_KEY", sessionId: "my-session-123", humanId: "internal-user-id-42", clientName: "my-app", }); // Per-call override await client.search("hello", { sessionId: "ad-hoc-session" }); ``` -------------------------------- ### GET /research/{requestId} Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/endpoints.md Retrieves the status and result of an asynchronous research task by its request ID. The SDK calls this endpoint from the getResearch() method, optionally including usage information. ```APIDOC ## GET /research/{requestId} ### Description Retrieves the status and result of an asynchronous research task by its request ID. The SDK calls this endpoint from the getResearch() method, optionally including usage information. ### Method GET ### Endpoint /research/{requestId} ### Parameters #### Path Parameters - **requestId** (string) - Required - The unique identifier of the research request. #### Query Parameters - **include_usage** (boolean) - Optional - When set, includes usage information in the response. ### Response #### Success Response (200) - **requestId** (string) - The unique identifier of the research request. - **createdAt** (string) - The timestamp when the research request was created. - **status** (string) - The current status of the research task (e.g., queued, running, completed). - **content** (string | Record<string, any>) - The research content, either as a string or structured object. - **sources** (Array<{title, url}>) - List of sources with title and URL. - **responseTime** (number) - The time taken to generate the response. - **usage** (object) - Optional - Usage information, present when include_usage is set. #### Response Example { "requestId": "string", "createdAt": "string", "status": "string", "content": "string | Record<string, any>", "sources": [ { "title": "string", "url": "string" } ], "responseTime": 0, "usage": {} } ``` -------------------------------- ### Tavily Search with exactMatch Option Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Use the exactMatch option to only return results containing the exact phrase(s) inside quotes. The example searches for '"John Smith" CEO Acme Corp'. ```javascript const { tavily } = require("@tavily/core"); const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Use exactMatch: true to only return results containing the exact phrase(s) inside quotes const response = await tvly.search('"John Smith" CEO Acme Corp', { exactMatch: true, }); console.log(response); ``` -------------------------------- ### Initialization with proxies, organization scoping, and session tracking Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/tavily.md Initializes the Tavily client with additional options: proxies (HTTP and HTTPS supported), projectId, orgId, sessionId, humanId, clientName, and clientSource. These options enable proxy usage, organization scoping, and session tracking. ```TypeScript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY", proxies: { http: "http://proxy.local:8080" }, // https also supported projectId: "proj_123", orgId: "org_456", sessionId: "my-session-123", humanId: "internal-user-id-42", clientName: "my-app", clientSource: "my-custom-client", }); ``` -------------------------------- ### Tavily Keyless Mode with Error Handling Source: https://github.com/tavily-ai/tavily-js/blob/main/README.md Run Tavily without an API key by omitting apiKey. In keyless mode, search and extract are available with a shared rate limit; other methods throw an error. The example catches TavilyKeylessLimitError and logs structured fields like capType, retryAfter, bonusEligible, and continuationPaths. ```javascript const { tavily, TavilyKeylessLimitError } = require("@tavily/core"); // No apiKey — keyless mode const tvly = tavily(); try { const response = await tvly.search("Who is Leo Messi?"); console.log(response); } catch (err) { if (err instanceof TavilyKeylessLimitError) { // Rate-limit cap hit. Inspect structured fields to decide what to do next. console.log("cap:", err.capType); console.log("retry after:", err.retryAfter); console.log("bonus eligible:", err.bonusEligible); console.log("continuation options:", err.continuationPaths); } else { throw err; } } ``` -------------------------------- ### Keyless initialization and keyless-limit error handling Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/tavily.md Initializes the Tavily client without an API key (keyless mode) and demonstrates handling the TavilyKeylessLimitError. The error provides cap type, retry-after, bonus eligibility, and continuation options. Also shows that crawl() throws synchronously in keyless mode. ```TypeScript import { tavily, TavilyKeylessLimitError } from "@tavily/core"; // No apiKey, no TAVILY_API_KEY env var → keyless mode const tvly = tavily(); try { const response = await tvly.search("Who is Leo Messi?"); console.log(response); } catch (err) { if (err instanceof TavilyKeylessLimitError) { console.log("cap:", err.capType); console.log("retry after:", err.retryAfter); console.log("bonus eligible:", err.bonusEligible); console.log("continuation options:", err.continuationPaths); } else { throw err; } } // These throw synchronously with Error("crawl: Keyless mode only supports search and extract; provide an API key to use this method.") await tvly.crawl("https://example.com"); // throws ``` -------------------------------- ### Catch Tavily errors with TavilyKeylessLimitError and Error checks Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/errors.md Use this snippet to handle errors from Tavily API calls. Check for TavilyKeylessLimitError first using instanceof, then handle other Error instances by inspecting the message for timeouts, keyless mode restrictions, or generic errors. The example uses keyless mode and logs structured fields from the limit error. ```TypeScript import { tavily, TavilyKeylessLimitError } from "@tavily/core"; const tvly = tavily(); // keyless try { const res = await tvly.search("hello world", { includeUsage: true }); console.log(res.results.length); } catch (err) { if (err instanceof TavilyKeylessLimitError) { // Cap reached — structured fields tell you what to do next. console.log("cap:", err.capType); console.log("retry after (s):", err.retryAfter); console.log("bonus eligible:", err.bonusEligible); console.log("next actions:", err.continuationPaths); const bonus = err.continuationPaths.find((p) => p.type === "bonus_credits"); if (bonus?.type === "bonus_credits" && bonus.eligible) { console.log("earn more credits via", bonus.endpoint, bonus.questions); } } else if (err instanceof Error) { if (/timed out after \d+ seconds/.test(err.message)) { // Retry with a larger `timeout` option for this call. } else if (err.message.includes("Keyless mode only supports search and extract")) { // Provide an API key: tavily({ apiKey: "..." }) or set TAVILY_API_KEY. } else { // Either detail.error from the API, `${status} Error: ...`, or the // "An unexpected error occurred..." wrapper. } } else { throw err; } } ``` -------------------------------- ### Basic search call with advanced options Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/search.md Initializes the Tavily client with an API key and performs a search with advanced options like searchDepth, topic, days, maxResults, includeAnswer, includeRawContent, includeImages, and includeUsage. Logs the answer, results, requestId, and credits. ```typescript import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); const response = await tvly.search("latest AI regulations in the EU", { searchDepth: "advanced", topic: "news", days: 7, maxResults: 10, includeAnswer: "advanced", includeRawContent: "markdown", includeImages: true, includeUsage: true, }); console.log(response.answer); for (const result of response.results) { console.log(result.title, result.url, result.score, result.publishedDate); } console.log("requestId:", response.requestId, "credits:", response.usage?.credits); ``` -------------------------------- ### POST /search (searchContext) Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/legacy-search.md Deprecated client method `searchContext()` that maps to POST /search and returns the search context (a list of content strings). It is deprecated and will be removed in a future version; use `search()` with `includeAnswer: false` instead. ```APIDOC ## [POST] /search ### Description Deprecated client method that performs a search and returns the search context (a list of content strings). It maps to the `/search` endpoint with `includeAnswer` always set to `false`. This method is deprecated and will be removed in a future version; use `search()` with `includeAnswer: false` instead. ### Method POST ### Endpoint /search ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body - **query** (string) - Required - Search query. - **search_depth** (string) - Optional - Default: `"advanced"`. Search depth. - **topic** (string) - Optional - Topic filter. - **days** (number) - Optional - Number of days to search. - **max_results** (number) - Optional - Maximum number of results. - **include_answer** (boolean) - Always `false`. - **include_domains** (array of strings) - Optional - Domains to include. - **exclude_domains** (array of strings) - Optional - Domains to exclude. - **chunks_per_source** (number) - Optional - Chunks per source. - **include_favicon** (boolean) - Optional - Include favicon. ### Request Example ```json { "query": "What is the capital of France?", "search_depth": "advanced", "max_results": 5, "include_answer": false } ``` ### Response #### Success Response (200) - **context** (array of strings) - The search context, a list of content strings. #### Response Example ```json { "context": ["Paris is the capital of France."] } ``` ### Error Handling - **Error** - Keyless client: thrown synchronously with message `searchContext: Keyless mode only supports search and extract; provide an API key to use this method.` - **Error** - Request timed out after 60 seconds (default) on axios `ECONNABORTED`. - **Error** / **TavilyKeylessLimitError** - API error response via `handleRequestError`. - **Error** - Wrapper: `An unexpected error occurred while making the request. Error: ${err}`. ``` -------------------------------- ### tavily(options?: TavilyClientOptions): TavilyClient Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/README.md Factory function that creates a Tavily client instance. Accepts optional client options and returns a TavilyClient object. ```APIDOC ## tavily(options?: TavilyClientOptions): TavilyClient ### Description Creates a new Tavily client instance. This is the main entry point for interacting with the Tavily API. ### Method Factory function ### Signature `tavily(options?: TavilyClientOptions): TavilyClient` ### Parameters - **options** (TavilyClientOptions) - Optional - Configuration options for the client. ### Returns - **TavilyClient** - A client instance with methods for various Tavily operations. ### Example ```typescript import { tavily } from '@tavily/core'; const client = tavily({ apiKey: 'your-api-key' }); ``` ``` -------------------------------- ### client.searchContext(query, options) Source: https://github.com/tavily-ai/tavily-js/blob/main/_autodocs/api-reference/legacy-search.md Deprecated method that performs a search and returns a JSON string of context snippets. Use `search()` instead. ```APIDOC ## `client.searchContext(query, options)` ### Description Deprecated method that performs a search and returns a JSON string of context snippets. Use `search()` directly and process the results as needed. ### Method `searchContext` (SDK method) ### Endpoint N/A (SDK method) ### Parameters - **query** (`string`) - Required - Search query. - **options** (`TavilySearchOptions`) - Optional (default `{}`) - Same type as `search()` options; only the fields below are sent. Request body sent: `query`, `search_depth`, `topic`, `days`, `max_results`, `include_domains`, `exclude_domains`, `chunks_per_source`, `include_favicon`. Request timeout defaults to 60 s. `maxTokens` is **not** sent to the API — it is applied client-side. ### Return Type `Promise<string>` — a JSON string. The client maps the server results to `[{ url, content }]` objects and truncates the list so that the token count of the serialized array does not exceed `options.maxTokens ?? 4000`. Token counting uses js-tiktoken with the `gpt-3.5-turbo` encoding. ### Throws / Rejects - `Error` - Keyless client — thrown synchronously: `` `searchContext: Keyless mode only supports search and extract; provide an API key to use this method.` `` - `Error` - `Request timed out after ${timeout} seconds.` on axios `ECONNABORTED` (default 60 s) - `Error` / `TavilyKeylessLimitError` - API error response via `handleRequestError` - `Error` - Wrapper: `An unexpected error occurred while making the request. Error: ${err}` ### Usage Example ```ts import { tavily } from "@tavily/core"; const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" }); // Deprecated — prefer search() and build context yourself const contextJson = await tvly.searchContext("Tavily SDK", { maxTokens: 2000, maxResults: 10, }); const context = JSON.parse(contextJson); // [{ url, content }, ...] console.log(context.length, "sources fit within the token budget"); ``` Both methods emit `console.warn("... is deprecated and will be removed in a future version. ...")` on each invocation. ```