> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Tavily 搜索集成

> 通过LangChain JavaScript与Tavily搜索工具集成。

[Tavily的搜索API](https://tavily.com/) 是专为AI智能体（LLM）构建的搜索引擎，能够实时、精准、快速地提供事实性结果。

## 概述

### 集成细节

| 类 | 包 | [PY支持](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/tools/tavily_search.md) | 下载量 | 版本 |
| :- | :- | :-: | :-: | :-: |
| [`TavilySearch`](https://reference.langchain.com/javascript/langchain-tavily/TavilySearch) | [`@langchain/tavily`](https://www.npmjs.com/package/@langchain/tavily) | ✅ | ![NPM - 下载量](https://img.shields.io/npm/dm/@langchain/tavily?style=flat-square\&label=%20&) | ![NPM - 版本](https://img.shields.io/npm/v/@langchain/tavily?style=flat-square\&label=%20&) |

### 工具特性

| [返回工件](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md) | 原生异步 | 返回数据 | 定价 |
| :-: | :-: | :-: | :-: |
| ❌ | ✅ | 标题、URL、内容片段、原始内容、答案、图片 | 每月1,000次免费搜索 |

## 设置

集成位于`@langchain/tavily`包中，您可以通过以下方式安装：

```bash npm theme={null}
npm install @langchain/tavily @langchain/core
```

```bash yarn theme={null}
yarn add @langchain/tavily @langchain/core
```

```bash pnpm theme={null}
pnpm add @langchain/tavily @langchain/core
```

### 凭证

[设置Tavily API密钥](https://app.tavily.com)并将其设置为名为`TAVILY_API_KEY`的环境变量。

```typescript theme={null}
process.env.TAVILY_API_KEY = "YOUR_API_KEY"
```

此外，设置[LangSmith](https://smith.langchain.com)有助于实现最佳级别的可观察性（但非必需）：

```typescript theme={null}
process.env.LANGSMITH_TRACING="true"
process.env.LANGSMITH_API_KEY="your-api-key"
```

## 实例化

该工具在实例化期间接受各种参数：

* `maxResults`（可选，数字）：返回的最大搜索结果数量。默认值为`5`。
* `topic`（可选，字符串）：搜索类别。可以是`"general"`、`"news"`或`"finance"`。默认值为`"general"`。
* `includeAnswer`（可选，布尔值）：在结果中包含对原始查询的答案。默认值为`false`。
* `includeRawContent`（可选，布尔值 | `"markdown"` | `"text"`）：包含每个搜索结果的清理和解析内容。默认值为`false`。
* `includeImages`（可选，布尔值）：在响应中包含与查询相关的图片列表。默认值为`false`。
* `includeImageDescriptions`（可选，布尔值）：包含每张图片的描述性文本。默认值为`false`。
* `searchDepth`（可选，字符串）：搜索深度，为`"basic"`或`"advanced"`。默认值为`"basic"`。
* `timeRange`（可选，字符串）：从当前日期过滤结果的时区范围 — `"day"`、`"week"`、`"month"`或`"year"`。默认值为`undefined`。
* `includeDomains`（可选，字符串\[]）：要特别包含的域名。默认值为`[]`。
* `excludeDomains`（可选，字符串\[]）：要特别排除的域名。默认值为`[]`。

有关可用参数的全面概述，请参阅[Tavily搜索API文档](https://docs.tavily.com/documentation/api-reference/endpoint/search)。

```typescript theme={null}
import { TavilySearch } from "@langchain/tavily";

const tool = new TavilySearch({
  maxResults: 5,
  topic: "general",
  // includeAnswer: false,
  // includeRawContent: false,
  // includeImages: false,
  // includeImageDescriptions: false,
  // searchDepth: "basic",
  // timeRange: "day",
  // includeDomains: [],
  // excludeDomains: [],
});
```

## 调用

### [使用参数直接调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md)

Tavily搜索工具在调用期间接受以下参数：

* `query`（必需）：自然语言搜索查询。
* 以下参数也可以在调用期间设置：`includeImages`、`searchDepth`、`timeRange`、`includeDomains`、`excludeDomains`。
* 出于可靠性和性能的考虑，某些影响响应大小的参数在调用期间不能修改：`includeAnswer`和`includeRawContent`。这些限制可防止意外的上下文窗口问题并确保结果的一致性。

注意：可选参数可用于智能体动态设置。如果您在实例化期间设置了一个参数，然后使用不同的值调用工具，工具将使用您在调用期间传递的值。

```typescript theme={null}
await tool.invoke({ query: "What happened at the last wimbledon" });
```

### [使用ToolCall调用](https://langchain-docs-zh.mintlify.site/langchain/oss/langchain/tools.md)

我们也可以使用模型生成的`ToolCall`调用工具，此时将返回一个@\[`ToolMessage`]：

```typescript theme={null}
// This is usually generated by a model, but we'll create a tool call directly for demo purposes.
const modelGeneratedToolCall = {
  args: { query: "euro 2024 host nation" },
  id: "1",
  name: tool.name,
  type: "tool_call",
};

const toolMsg = await tool.invoke(modelGeneratedToolCall);

// The content is a JSON string of results
console.log(toolMsg.content.slice(0, 400));
```

```json theme={null}
{"query": "euro 2024 host nation", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "UEFA Euro 2024 - Wikipedia", "url": "https://en.wikipedia.org/wiki/UEFA_Euro_2024", "content": "Tournament details Host country Germany Dates 14 June – 14 July Teams 24 Venue(s) 10 (in 10 host cities) Final positions Champions Spain (4th title) Runners-up England Tournament statisti
```

## 在智能体中使用

我们可以通过将其传递给`createAgent`直接使用搜索工具与LangChain智能体。智能体可以动态设置`includeDomains`、`searchDepth`和`timeRange`等参数作为其工具调用的一部分。

在以下示例中，当我们要求智能体查找“哪个国家举办了2024年欧洲杯？仅包含维基百科来源。”时，智能体会动态设置参数并使用`{ query: "Euro 2024 host nation", includeDomains: ["wikipedia.org"] }`调用Tavily搜索工具。

```typescript theme={null}
// @lc-docs-hide-cell
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "gpt-5.5",
  temperature: 0,
});
```

```typescript theme={null}
import { TavilySearch } from "@langchain/tavily";
import { createAgent } from "langchain";

// Initialize Tavily Search Tool
const tavilySearchTool = new TavilySearch({
  maxResults: 5,
  topic: "general",
});

const agent = createAgent({
  model: llm,
  tools: [tavilySearchTool],
});

const userInput = "What nation hosted Euro 2024? Include only wikipedia sources.";

const stream = await agent.streamEvents(
  { messages: [["human", userInput]] },
  { version: "v3" },
);

for await (const snapshot of stream.values) {
  const lastMsg = snapshot.messages[snapshot.messages.length - 1];
  if (lastMsg.tool_calls?.length) {
    console.dir(lastMsg.tool_calls, { depth: null });
  } else if (lastMsg.content) {
    console.log(lastMsg.content);
  }
}
```

***

## API参考

有关Tavily搜索API所有特性和配置的详细文档，请前往API参考：[docs.tavily.com/documentation/api-reference/endpoint/search](https://docs.tavily.com/documentation/api-reference/endpoint/search)

***

> 官方原文：[src/oss/javascript/integrations/tools/tavily\_search.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/tools/tavily_search.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.