Skip to main content

Tavily 提取

Tavily 是专为 AI 代理(LLMs)构建的搜索引擎,能够快速提供实时、准确且基于事实的结果。Tavily 提供了四个关键端点,其中之一是提取(Extract),它可以从 URL 中提供原始提取的内容。

本指南简要概述了如何开始使用 Tavily 工具。如需对 Tavily 工具的详细说明,您可以在 API 参考文档 中找到更详细的信息。

概述

集成详情

类别PY 支持包最新版本
TavilyExtract@langchain/tavilyNPM - 版本

安装设置

该集成位于 @langchain/tavily 包中,您可以按照以下方式安装:

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

yarn add @langchain/tavily @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";

实例化

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

import { TavilyExtract } from "@langchain/tavily";

const tool = new TavilyExtract({
extractDepth: "basic",
includeImages: false,
});

调用

使用参数直接调用

Tavily Extract 工具在调用期间接受以下参数:

  • urls(必填):要从中提取内容的 URL 列表。

  • 在调用期间也可以设置 extractDepthincludeImages

await tool.invoke({
urls: ["https://en.wikipedia.org/wiki/Lionel_Messi"],
});

使用工具调用调用

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

// This is usually generated by a model, but we'll create a tool call directly for demo purposes.
const modelGeneratedToolCall = {
args: { urls: ["https://en.wikipedia.org/wiki/Lionel_Messi"] },
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(
"['https://en.wikipedia.org/wiki/Albert_Einstein','https://en.wikipedia.org/wiki/Theoretical_physics']"
);
const { tool_calls, content } = toolChainResult;

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

代理

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

API 参考文档

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

https://docs.tavily.com/documentation/api-reference/endpoint/extract

相关内容


Was this page helpful?


You can also leave detailed feedback on GitHub.