Skip to main content

Tavily搜索结果(已弃用)

弃用通知

此工具已被弃用。请改用 @langchain/tavily 包中的 TavilySearch 工具。

Tavily 搜索是一个专为 LLM 代理定制的强大搜索 API。它能够与各种数据源无缝集成,以确保更高级别、更相关的搜索体验。

本指南提供了开始使用 Tavily 工具 的快速概览。如需关于 Tavily 工具的完整详细文档,您可以在 API 参考文档 中找到。

概览

集成详情

类名包名Python 支持最新包版本
TavilySearchResults@langchain/communityNPM - 版本

安装配置

该集成在 @langchain/community 包中,您可以按如下方式安装:

:::提示 请参阅安装集成包的一般说明部分。 :::

yarn add @langchain/community @langchain/core

凭证

在此处 链接 设置一个 API 密钥,并将其设置为名为 TAVILY_API_KEY 的环境变量。

process.env.TAVILY_API_KEY = "YOUR_API_KEY";

另外,设置 LangSmith 以获得最佳观测能力也是有帮助的(但不是必需的):

process.env.LANGSMITH_TRACING = "true";
process.env.LANGSMITH_API_KEY = "your-api-key";

实例化

你可以通过以下方式导入并实例化 TavilySearchResults 工具:

import { TavilySearchResults } from "@langchain/community/tools/tavily_search";

const tool = new TavilySearchResults({
maxResults: 2,
// ...
});

调用

使用参数直接调用

你可以像这样直接调用工具:

await tool.invoke({
input: "what is the current weather in SF?",
});

使用工具调用调用

我们还可以使用模型生成的 ToolCall 来调用工具,在这种情况下将返回 ToolMessage

// This is usually generated by a model, but we'll create a tool call directly for demo purposes.
const modelGeneratedToolCall = {
args: {
query: "what is the current weather in SF?",
},
id: "1",
name: tool.name,
type: "tool_call",
};

await tool.invoke(modelGeneratedToolCall);

链式调用

我们可以通过首先将其绑定到一个工具调用模型,然后调用它,以实现链式使用:

Pick your chat model:

Install dependencies

yarn add @langchain/groq 

Add environment variables

GROQ_API_KEY=your-api-key

Instantiate the model

import { ChatGroq } from "@langchain/groq";

const llm = new ChatGroq({
model: "llama-3.3-70b-versatile",
temperature: 0
});
import { HumanMessage } from "@langchain/core/messages";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { RunnableLambda } from "@langchain/core/runnables";

const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a helpful assistant."],
["placeholder", "{messages}"],
]);

const llmWithTools = llm.bindTools([tool]);

const chain = prompt.pipe(llmWithTools);

const toolChain = RunnableLambda.from(async (userInput: string, config) => {
const humanMessage = new HumanMessage(userInput);
const aiMsg = await chain.invoke(
{
messages: [new HumanMessage(userInput)],
},
config
);
const toolMsgs = await tool.batch(aiMsg.tool_calls, config);
return chain.invoke(
{
messages: [humanMessage, aiMsg, ...toolMsgs],
},
config
);
});

const toolChainResult = await toolChain.invoke(
"what is the current weather in sf?"
);
const { tool_calls, content } = toolChainResult;

console.log(
"AIMessage",
JSON.stringify(
{
tool_calls,
content,
},
null,
2
)
);

代理

关于如何在代理中使用 LangChain 工具的指南,请参阅 LangGraph.js 文档。

API 参考文档

如需详细了解所有 TavilySearchResults 的功能和配置,请前往 API 参考文档:

https://api.js.langchain.com/classes/langchain_community_tools_tavily_search.TavilySearchResults.html

相关内容


Was this page helpful?


You can also leave detailed feedback on GitHub.