TavilySearchResults
Tavily 搜索是一个强大的搜索 API,专门为 LLM 代理量身定制。它与各种数据源无缝集成,以确保卓越的相关搜索体验。
本指南提供了使用 Tavily 搜索结果 工具 入门的快速概述。有关所有 TavilySearchResults
功能和配置的详细文档,请访问 API 参考。
概述
集成详细信息
类 | 包 | PY 支持 | 最新包 |
---|---|---|---|
TavilySearchResults | @langchain/community | ✅ |
设置
该集成位于 @langchain/community
包中,您可以按照以下步骤安装:
有关安装集成包的常规说明,请参阅本节。
- npm
- yarn
- pnpm
npm i @langchain/community @langchain/core
yarn add @langchain/community @langchain/core
pnpm add @langchain/community @langchain/core
凭据
在此处设置 API 密钥 此处 并将其设置为名为 TAVILY_API_KEY
的环境变量。
process.env.TAVILY_API_KEY = "YOUR_API_KEY";
设置 LangSmith 以获得一流的可观察性也是很有帮助的(但不是必需的)。
process.env.LANGCHAIN_TRACING_V2 = "true";
process.env.LANGCHAIN_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?",
});
[{"title":"San Francisco, CA Current Weather | AccuWeather","url":"https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629","content":"Current weather in San Francisco, CA. Check current conditions in San Francisco, CA with radar, hourly, and more.","score":0.9428234,"raw_content":null},{"title":"National Weather Service","url":"https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA","content":"NOAA National Weather Service. Current conditions at SAN FRANCISCO DOWNTOWN (SFOC1) Lat: 37.77056°NLon: 122.42694°WElev: 150.0ft.","score":0.94261247,"raw_content":null}]
使用 ToolCall 调用
我们还可以使用模型生成的 ToolCall
调用该工具,在这种情况下,将返回 ToolMessage
// This is usually generated by a model, but we'll create a tool call directly for demo purposes.
const modelGeneratedToolCall = {
args: {
input: "what is the current weather in SF?",
},
id: "1",
name: tool.name,
type: "tool_call",
};
await tool.invoke(modelGeneratedToolCall);
ToolMessage {
"content": "[{\"title\":\"Weather in San Francisco\",\"url\":\"https://www.weatherapi.com/\",\"content\":\"{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1722967498, 'localtime': '2024-08-06 11:04'}, 'current': {'last_updated_epoch': 1722967200, 'last_updated': '2024-08-06 11:00', 'temp_c': 18.4, 'temp_f': 65.2, 'is_day': 1, 'condition': {'text': 'Sunny', 'icon': '//cdn.weatherapi.com/weather/64x64/day/113.png', 'code': 1000}, 'wind_mph': 2.9, 'wind_kph': 4.7, 'wind_degree': 275, 'wind_dir': 'W', 'pressure_mb': 1015.0, 'pressure_in': 29.97, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 64, 'cloud': 2, 'feelslike_c': 18.5, 'feelslike_f': 65.2, 'windchill_c': 18.5, 'windchill_f': 65.2, 'heatindex_c': 18.4, 'heatindex_f': 65.2, 'dewpoint_c': 11.7, 'dewpoint_f': 53.1, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 5.0, 'gust_mph': 4.3, 'gust_kph': 7.0}}\",\"score\":0.9983156,\"raw_content\":null},{\"title\":\"Weather in San Francisco in June 2024 - Detailed Forecast\",\"url\":\"https://www.easeweather.com/north-america/united-states/california/city-and-county-of-san-francisco/san-francisco/june\",\"content\":\"Until now, June 2024 in San Francisco is slightly cooler than the historical average by -0.6 ° C.. The forecast for June 2024 in San Francisco predicts the temperature to closely align with the historical average at 17.7 ° C. 17.7 ° C.\",\"score\":0.9905143,\"raw_content\":null}]",
"name": "tavily_search_results_json",
"additional_kwargs": {},
"response_metadata": {},
"tool_call_id": "1"
}
链接
我们可以通过首先将工具绑定到 工具调用模型,然后调用它来在链中使用我们的工具
选择您的聊天模型
- OpenAI
- Anthropic
- FireworksAI
- MistralAI
- Groq
- VertexAI
安装依赖项
请参阅 本节,了解有关安装集成包的常规说明。.
- npm
- yarn
- pnpm
npm i @langchain/openai
yarn add @langchain/openai
pnpm add @langchain/openai
添加环境变量
OPENAI_API_KEY=your-api-key
实例化模型
import { ChatOpenAI } from "@langchain/openai";
const llm = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0
});
安装依赖项
请参阅 本节,了解有关安装集成包的常规说明。.
- npm
- yarn
- pnpm
npm i @langchain/anthropic
yarn add @langchain/anthropic
pnpm add @langchain/anthropic
添加环境变量
ANTHROPIC_API_KEY=your-api-key
实例化模型
import { ChatAnthropic } from "@langchain/anthropic";
const llm = new ChatAnthropic({
model: "claude-3-5-sonnet-20240620",
temperature: 0
});
安装依赖项
请参阅 本节,了解有关安装集成包的常规说明。.
- npm
- yarn
- pnpm
npm i @langchain/community
yarn add @langchain/community
pnpm add @langchain/community
添加环境变量
FIREWORKS_API_KEY=your-api-key
实例化模型
import { ChatFireworks } from "@langchain/community/chat_models/fireworks";
const llm = new ChatFireworks({
model: "accounts/fireworks/models/llama-v3p1-70b-instruct",
temperature: 0
});
安装依赖项
请参阅 本节,了解有关安装集成包的常规说明。.
- npm
- yarn
- pnpm
npm i @langchain/mistralai
yarn add @langchain/mistralai
pnpm add @langchain/mistralai
添加环境变量
MISTRAL_API_KEY=your-api-key
实例化模型
import { ChatMistralAI } from "@langchain/mistralai";
const llm = new ChatMistralAI({
model: "mistral-large-latest",
temperature: 0
});
安装依赖项
请参阅 本节,了解有关安装集成包的常规说明。.
- npm
- yarn
- pnpm
npm i @langchain/groq
yarn add @langchain/groq
pnpm add @langchain/groq
添加环境变量
GROQ_API_KEY=your-api-key
实例化模型
import { ChatGroq } from "@langchain/groq";
const llm = new ChatGroq({
model: "mixtral-8x7b-32768",
temperature: 0
});
安装依赖项
请参阅 本节,了解有关安装集成包的常规说明。.
- npm
- yarn
- pnpm
npm i @langchain/google-vertexai
yarn add @langchain/google-vertexai
pnpm add @langchain/google-vertexai
添加环境变量
GOOGLE_APPLICATION_CREDENTIALS=credentials.json
实例化模型
import { ChatVertexAI } from "@langchain/google-vertexai";
const llm = new ChatVertexAI({
model: "gemini-1.5-flash",
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
)
);
AIMessage {
"tool_calls": [],
"content": "The current weather in San Francisco is as follows:\n\n- **Condition:** Sunny\n- **Temperature:** 18.4°C (65.2°F)\n- **Wind:** 2.9 mph (4.7 kph) from the west\n- **Humidity:** 64%\n- **Visibility:** 10 km (6 miles)\n- **UV Index:** 5\n\n![Sunny](//cdn.weatherapi.com/weather/64x64/day/113.png)\n\nFor more detailed information, you can visit [WeatherAPI](https://www.weatherapi.com/)."
}
代理
有关如何在代理中使用 LangChain 工具的指南,请参阅 LangGraph.js 文档。
API 参考
有关所有 TavilySearchResults
功能和配置的详细文档,请访问 API 参考:https://api.js.langchain.com/classes/langchain_community_tools_tavily_search.TavilySearchResults.html