mirror of
https://github.com/hwchase17/langchain
synced 2024-11-10 01:10:59 +00:00
docs: standardizing tavily tool docs (#24736)
Co-authored-by: Bagatur <22008038+baskaryan@users.noreply.github.com> Co-authored-by: Bagatur <baskaryan@gmail.com>
This commit is contained in:
parent
2ae76cecde
commit
73570873ab
@ -15,20 +15,47 @@
|
||||
"source": [
|
||||
"[Tavily's Search API](https://tavily.com) is a search engine built specifically for AI agents (LLMs), delivering real-time, accurate, and factual results at speed.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"\n",
|
||||
"### Integration details\n",
|
||||
"| Class | Package | Serializable | [JS support](https://js.langchain.com/v0.2/docs/integrations/tools/tavily_search) | Package latest |\n",
|
||||
"| :--- | :--- | :---: | :---: | :---: |\n",
|
||||
"| [TavilySearchResults](https://api.python.langchain.com/en/latest/tools/langchain_community.tools.tavily_search.tool.TavilySearchResults.html) | [langchain-community](https://api.python.langchain.com/en/latest/community_api_reference.html) | ❌ | ✅ | ![PyPI - Version](https://img.shields.io/pypi/v/langchain-community?style=flat-square&label=%20) |\n",
|
||||
"\n",
|
||||
"### Tool features\n",
|
||||
"| [Returns artifact](/docs/how_to/tool_artifacts/) | Native async | Return data | Pricing |\n",
|
||||
"| :---: | :---: | :---: | :---: |\n",
|
||||
"| ✅ | ✅ | Title, URL, content, answer | 1,000 free searches / month | \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"## Setup\n",
|
||||
"\n",
|
||||
"The integration lives in the `langchain-community` package. We also need to install the `tavily-python` package itself.\n",
|
||||
"\n",
|
||||
"```bash\n",
|
||||
"pip install -U langchain-community tavily-python\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"We also need to set our Tavily API key."
|
||||
"The integration lives in the `langchain-community` package. We also need to install the `tavily-python` package."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f85b4089",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -qU \"langchain-community>=0.2.11\" tavily-python"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b15e9266",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Credentials\n",
|
||||
"\n",
|
||||
"We also need to set our Tavily API key. You can get an API key by visiting [this site](https://app.tavily.com/sign-in) and creating an account."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "e0b178a2-8816-40ca-b57c-ccdd86dde9c9",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@ -36,7 +63,8 @@
|
||||
"import getpass\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"os.environ[\"TAVILY_API_KEY\"] = getpass.getpass()"
|
||||
"if not os.environ.get(\"TAVILY_API_KEY\"):\n",
|
||||
" os.environ[\"TAVILY_API_KEY\"] = getpass.getpass(\"Tavily API key:\\n\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@ -44,12 +72,12 @@
|
||||
"id": "bc5ab717-fd27-4c59-b912-bdd099541478",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"It's also helpful (but not needed) to set up [LangSmith](https://smith.langchain.com/) for best-in-class observability"
|
||||
"It's also helpful (but not needed) to set up [LangSmith](https://smith.langchain.com/) for best-in-class observability:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 3,
|
||||
"id": "a6c2f136-6367-4f1f-825d-ae741e1bf281",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@ -63,166 +91,274 @@
|
||||
"id": "1c97218f-f366-479d-8bf7-fe9f2f6df73f",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Usage\n",
|
||||
"## Instantiation\n",
|
||||
"\n",
|
||||
"Here we show how to use the tool individually."
|
||||
"Here we show how to instatiate an instance of the Tavily search tools, with "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": 1,
|
||||
"id": "8b3ddfe9-ca79-494c-a7ab-1f56d9407a64",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
|
||||
"from langchain_community.tools import TavilySearchResults\n",
|
||||
"\n",
|
||||
"tool = TavilySearchResults()"
|
||||
"tool = TavilySearchResults(\n",
|
||||
" max_results=5,\n",
|
||||
" search_depth=\"advanced\",\n",
|
||||
" include_answer=True,\n",
|
||||
" include_raw_content=True,\n",
|
||||
" include_images=True,\n",
|
||||
" # include_domains=[...],\n",
|
||||
" # exclude_domains=[...],\n",
|
||||
" # name=\"...\", # overwrite default tool name\n",
|
||||
" # description=\"...\", # overwrite default tool description\n",
|
||||
" # args_schema=..., # overwrite default args_schema: BaseModel\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "74147a1a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Invocation\n",
|
||||
"\n",
|
||||
"### [Invoke directly with args](/docs/concepts/#invoke-with-just-the-arguments)\n",
|
||||
"\n",
|
||||
"The `TavilySearchResults` tool takes a single \"query\" argument, which should be a natural language query:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"execution_count": 2,
|
||||
"id": "65310a8b-eb0c-4d9e-a618-4f4abe2414fc",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[{'url': 'https://apnews.com/article/burning-man-flooding-nevada-stranded-3971a523f4b993f8f35e158fd1a17a1e',\n",
|
||||
" 'content': 'festival goers are helped off a truck from the Burning Man festival site in Black Rock, Nev., on Monday, Sept. 4, 2023. festival goers are helped off a truck from the Burning Man festival site in Black Rock, Nev., on Monday, Sept. 4, 2023. at the site of the Burning Man festival where thousands of attendees remained stranded as flooding from storms swept at the site of the Burning Man festival where thousands of attendees remained stranded as flooding from storms sweptRENO, Nev. (AP) — The traffic jam leaving the Burning Man festival eased up considerably Tuesday as the exodus from the mud-caked Nevada desert entered another day following massive rain that left tens of thousands of partygoers stranded for days.'},\n",
|
||||
" {'url': 'https://www.theguardian.com/culture/2023/sep/03/burning-man-nevada-festival-floods',\n",
|
||||
" 'content': 'Officials investigate death at Burning Man as thousands stranded by floods Burning Man festival-goers trapped in desert as rain turns site to mud the burning of a giant sculpture to cap off the event, if weather permits. The festival said the roads remain too wet Burning Man festivalgoers surrounded by mud in Nevada desert – videoMichael Sainato @msainat1 Sun 3 Sep 2023 14.31 EDT Over 70,000 attendees of the annual Burning Man festival in the Black Rock desert of Nevada are stranded as the festival comes to a close on...'},\n",
|
||||
" {'url': 'https://abcnews.go.com/US/burning-man-flooding-happened-stranded-festivalgoers/story?id=102908331',\n",
|
||||
" 'content': 'ABC News Video Live Shows Election 2024 538 Stream on Burning Man flooding: What happened to stranded festivalgoers? Tens of thousands of Burning Man attendees are now able to leave the festival after a downpour and massive flooding Burning Man has been hosted for over 30 years, according to a statement from the organizers. people last year, and just as many were expected this year. Burning Man began on Aug. 28 and was scheduled to runJulie Jammot/AFP via Getty Images Tens of thousands of Burning Man attendees are now able to leave the festival after a downpour and massive flooding left them stranded over the weekend. The festival, held in the Black Rock Desert in northwestern Nevada, was attended by more than 70,000 people last year, and just as many were expected this year.'},\n",
|
||||
" {'url': 'https://www.vox.com/culture/2023/9/6/23861675/burning-man-2023-mud-stranded-climate-change-playa-foot',\n",
|
||||
" 'content': 'This year’s rains opened the floodgates for Burning Man criticism Pray for him people #burningman #burningman2023 #titanicsound #mud #festival who went to Burning Man that large wooden Man won’t be the only one burning.Celebrity Culture The Burning Man flameout, explained Climate change — and schadenfreude — finally caught up to the survivalist cosplayers. By Aja Romano @ajaromano Sep 6, 2023, 3:00pm EDT Share'},\n",
|
||||
" {'url': 'https://www.cnn.com/2023/09/03/us/burning-man-storms-shelter-sunday/index.html',\n",
|
||||
" 'content': 'Editor’s Note: Find the latest Burning Man festival coverage here. CNN values your feedback More than 70,000 Burning Man festival attendees remain stuck in Nevada desert after rain Burning Man organizers said Sunday night. Thousands of people remain trapped at the Burning Man festival in the Nevada desert after heavy rains inundated the\"A mucky, muddy, environment.\" This is what Burning Man looks like See More Videos Editor\\'s Note: Find the latest Burning Man festival coverage here. CNN —'}]"
|
||||
"[{'url': 'https://www.theguardian.com/sport/live/2023/jul/16/wimbledon-mens-singles-final-2023-carlos-alcaraz-v-novak-djokovic-live?page=with:block-64b3ff568f08df28470056bf',\n",
|
||||
" 'content': 'Carlos Alcaraz recovered from a set down to topple Djokovic 1-6, 7-6(6), 6-1, 3-6, 6-4 and win his first Wimbledon title in a battle for the ages'},\n",
|
||||
" {'url': 'https://www.nytimes.com/athletic/live-blogs/wimbledon-2024-live-updates-alcaraz-djokovic-mens-final-result/kJJdTKhOgkZo/',\n",
|
||||
" 'content': \"It was Djokovic's first straight-sets defeat at Wimbledon since the 2013 final, when he lost to Andy Murray. Below, The Athletic 's writers, Charlie Eccleshare and Matt Futterman, analyze the ...\"},\n",
|
||||
" {'url': 'https://www.foxsports.com.au/tennis/wimbledon/fk-you-stars-explosion-stuns-wimbledon-as-massive-final-locked-in/news-story/41cf7d28a12845cdab6be4150a22a170',\n",
|
||||
" 'content': 'The last time Djokovic and Wimbledon met was at the French Open in June when the Serb claimed victory in a third round tie which ended at 3:07 in the morning. On Friday, however, Djokovic was ...'},\n",
|
||||
" {'url': 'https://www.cnn.com/2024/07/09/sport/novak-djokovic-wimbledon-crowd-quarterfinals-spt-intl/index.html',\n",
|
||||
" 'content': 'Novak Djokovic produced another impressive performance at Wimbledon on Monday to cruise into the quarterfinals, but the 24-time grand slam champion was far from happy after his win.'},\n",
|
||||
" {'url': 'https://www.cnn.com/2024/07/05/sport/andy-murray-wimbledon-farewell-ceremony-spt-intl/index.html',\n",
|
||||
" 'content': \"It was an emotional night for three-time grand slam champion Andy Murray on Thursday, as the 37-year-old's Wimbledon farewell began with doubles defeat.. Murray will retire from the sport this ...\"}]"
|
||||
]
|
||||
},
|
||||
"execution_count": 9,
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"tool.invoke({\"query\": \"What happened in the latest burning man floods\"})"
|
||||
"tool.invoke({\"query\": \"What happened at the last wimbledon\"})"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "21c5b56f-0da0-485f-b6f5-38950bae4fd0",
|
||||
"id": "d6e73897",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### [Invoke with ToolCall](/docs/concepts/#invoke-with-toolcall)\n",
|
||||
"\n",
|
||||
"We can also invoke the tool with a model-generated ToolCall, in which case a ToolMessage will be returned:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "f90e33a7",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[{\"url\": \"https://www.radiotimes.com/tv/sport/football/euro-2024-location/\", \"content\": \"Euro 2024 host cities. Germany have 10 host cities for Euro 2024, topped by the country's capital Berlin. Berlin. Cologne. Dortmund. Dusseldorf. Frankfurt. Gelsenkirchen. Hamburg.\"}, {\"url\": \"https://www.sportingnews.com/ca/soccer/news/list-euros-host-nations-uefa-european-championship-countries/85f8069d69c9f4\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# This is usually generated by a model, but we'll create a tool call directly for demon purposes.\n",
|
||||
"model_generated_tool_call = {\n",
|
||||
" \"args\": {\"query\": \"euro 2024 host nation\"},\n",
|
||||
" \"id\": \"1\",\n",
|
||||
" \"name\": \"tavily\",\n",
|
||||
" \"type\": \"tool_call\",\n",
|
||||
"}\n",
|
||||
"tool_msg = tool.invoke(model_generated_tool_call)\n",
|
||||
"\n",
|
||||
"# The content is a JSON string of results\n",
|
||||
"print(tool_msg.content[:400])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"id": "d8e27be0-1098-4688-8d8c-6e257aae8d56",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'query': str,\n",
|
||||
" 'follow_up_questions': NoneType,\n",
|
||||
" 'answer': str,\n",
|
||||
" 'images': list,\n",
|
||||
" 'results': list,\n",
|
||||
" 'response_time': float}"
|
||||
]
|
||||
},
|
||||
"execution_count": 20,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# The artifact is a dict with richer, raw results\n",
|
||||
"{k: type(v) for k, v in tool_msg.artifact.items()}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 21,
|
||||
"id": "237ca620-ac31-449a-826b-b4f2e265b194",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"{\n",
|
||||
" \"query\": \"euro 2024 host nation\",\n",
|
||||
" \"follow_up_questions\": \"None\",\n",
|
||||
" \"answer\": \"Germany will be the host nation for Euro 2024, with the tournament scheduled to take place from June 14 to July 14. The matches will be held in 10 different cities across Germany, including Berlin, Co\",\n",
|
||||
" \"images\": \"['https://i.ytimg.com/vi/3hsX0vLatNw/maxresdefault.jpg', 'https://img.planetafobal.com/2021/10/sedes-uefa-euro-2024-alemania-fg.jpg', 'https://editorial.uefa.com/resources/0274-14fe4fafd0d4-413fc8a7b7\",\n",
|
||||
" \"results\": \"[{'title': 'Where is Euro 2024? Country, host cities and venues', 'url': 'https://www.radiotimes.com/tv/sport/football/euro-2024-location/', 'content': \\\"Euro 2024 host cities. Germany have 10 host cit\",\n",
|
||||
" \"response_time\": \"3.97\"\n",
|
||||
"}\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import json\n",
|
||||
"\n",
|
||||
"# Abbreviate the results for demo purposes\n",
|
||||
"print(json.dumps({k: str(v)[:200] for k, v in tool_msg.artifact.items()}, indent=2))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "659f9fbd-6fcf-445f-aa8c-72d8e60154bd",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Chaining\n",
|
||||
"We show here how to use it as part of an [agent](/docs/tutorials/agents). We use the OpenAI Functions Agent, so we will need to setup and install the required dependencies for that. We will also use [LangSmith Hub](https://smith.langchain.com/hub) to pull the prompt from, so we will need to install that.\n",
|
||||
"\n",
|
||||
"```bash\n",
|
||||
"pip install -U langchain-openai langchainhub\n",
|
||||
"We can use our tool in a chain by first binding it to a [tool-calling model](/docs/how_to/tool_calling/) and then calling it:\n",
|
||||
"\n",
|
||||
"```{=mdx}\n",
|
||||
"import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
|
||||
"\n",
|
||||
"<ChatModelTabs customVarName=\"llm\" />\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "a1c8ea19-7100-407d-8e8c-f037f9317255",
|
||||
"id": "af3123ad-7a02-40e5-b58e-7d56e23e5830",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import getpass\n",
|
||||
"import os\n",
|
||||
"# | output: false\n",
|
||||
"# | echo: false\n",
|
||||
"\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = getpass.getpass()"
|
||||
"# !pip install -qU langchain langchain-openai\n",
|
||||
"from langchain.chat_models import init_chat_model\n",
|
||||
"\n",
|
||||
"llm = init_chat_model(model=\"gpt-4o\", model_provider=\"openai\", temperature=0)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "520767b8-9e61-4485-840a-d16f1da5eb3a",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2023-10-21T13:15:37.974229Z",
|
||||
"start_time": "2023-10-21T13:15:10.007898Z"
|
||||
}
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain import hub\n",
|
||||
"from langchain.agents import AgentExecutor, create_openai_functions_agent\n",
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"\n",
|
||||
"instructions = \"\"\"You are an assistant.\"\"\"\n",
|
||||
"base_prompt = hub.pull(\"langchain-ai/openai-functions-template\")\n",
|
||||
"prompt = base_prompt.partial(instructions=instructions)\n",
|
||||
"llm = ChatOpenAI(temperature=0)\n",
|
||||
"tavily_tool = TavilySearchResults()\n",
|
||||
"tools = [tavily_tool]\n",
|
||||
"agent = create_openai_functions_agent(llm, tools, prompt)\n",
|
||||
"agent_executor = AgentExecutor(\n",
|
||||
" agent=agent,\n",
|
||||
" tools=tools,\n",
|
||||
" verbose=True,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "e9303451-3853-47ce-93c9-1898436a6472",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2023-10-21T13:15:37.974229Z",
|
||||
"start_time": "2023-10-21T13:15:10.007898Z"
|
||||
}
|
||||
},
|
||||
"execution_count": 23,
|
||||
"id": "fdbf35b5-3aaf-4947-9ec6-48c21533fb95",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"\n",
|
||||
"\n",
|
||||
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
|
||||
"\u001b[32;1m\u001b[1;3m\n",
|
||||
"Invoking: `tavily_search_results_json` with `{'query': 'latest burning man floods'}`\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.politifact.com/factchecks/2023/sep/06/instagram-posts/there-were-floods-there-was-mud-but-burning-man-sp/', 'content': 'The Associated Press, Burning Man flooding triggers false claims of Ebola outbreak, ‘national emergency,’ Sept. 5, 2023 BBC, Thousands queue for hours to leave Burning Man festival, Sept. 5, 2023 Newsweek, Is FEMA at Burning Man? Virus Outbreak Conspiracy Theory Spreads Online, Sept. 4, 2023 CBS News, Burning Man \"exodus operations\" begin as driving ban is lifted, organizers say, Sept. 4, 2023(AP) By Madison Czopek September 6, 2023 There were floods, there was mud, but Burning Man sparked no emergency declaration If Your Time is short Heavy rain began falling Sept. 1 in Nevada\\'s...'}, {'url': 'https://www.nbcnews.com/news/us-news/live-blog/live-updates-burning-man-flooding-keeps-thousands-stranded-nevada-site-rcna103193', 'content': 'As heavy rain turns Burning Man 2023 into a muddy mess, a deluge of unsympathetic jokes has swamped the internet Burning Man flooding keeps thousands stranded at Nevada site as authorities investigate 1 death Burning Man revelers unfazed by deluge and deep mud Reuters The flash flood watch is in effect until tomorrow morning. Burning Man is ‘absolutely soaked,’ festivalgoer saysThousands of Burning Man attendees partied hard on Sunday despite downpours that turned the Nevada desert where the annual arts and music festival takes place into a sea of sticky mud and led...'}, {'url': 'https://apnews.com/article/burning-man-flooding-nevada-stranded-3971a523f4b993f8f35e158fd1a17a1e', 'content': 'festival goers are helped off a truck from the Burning Man festival site in Black Rock, Nev., on Monday, Sept. 4, 2023. festival goers are helped off a truck from the Burning Man festival site in Black Rock, Nev., on Monday, Sept. 4, 2023. at the site of the Burning Man festival where thousands of attendees remained stranded as flooding from storms swept at the site of the Burning Man festival where thousands of attendees remained stranded as flooding from storms sweptRENO, Nev. (AP) — The traffic jam leaving the Burning Man festival eased up considerably Tuesday as the exodus from the mud-caked Nevada desert entered another day following massive rain that left tens of thousands of partygoers stranded for days.'}, {'url': 'https://apnews.com/article/burning-man-flooding-nevada-stranded-0726190c9f8378935e2a3cce7f154785', 'content': 'festival goers are helped off a truck from the Burning Man festival site in Black Rock, Nev., on Monday, Sept. 4, 2023. festival goers are helped off a truck from the Burning Man festival site in Black Rock, Nev., on Monday, Sept. 4, 2023. at the site of the Burning Man festival where thousands of attendees remained stranded as flooding from storms swept Wait times to exit Burning Man drop after flooding left tens of thousands stranded in Nevada desertFILE - In this satellite photo provided by Maxar Technologies, an overview of Burning Man festival in Black Rock, Nev on Monday, Aug. 28, 2023. Authorities in Nevada were investigating a death at the site of the Burning Man festival where thousands of attendees remained stranded as flooding from storms swept through the Nevada desert.'}, {'url': 'https://www.theguardian.com/culture/2023/sep/03/burning-man-nevada-festival-floods', 'content': 'Officials investigate death at Burning Man as thousands stranded by floods Burning Man festival-goers trapped in desert as rain turns site to mud the burning of a giant sculpture to cap off the event, if weather permits. The festival said the roads remain too wet Burning Man festivalgoers surrounded by mud in Nevada desert – videoMichael Sainato @msainat1 Sun 3 Sep 2023 14.31 EDT Over 70,000 attendees of the annual Burning Man festival in the Black Rock desert of Nevada are stranded as the festival comes to a close on...'}]\u001b[0m\u001b[32;1m\u001b[1;3mThe latest Burning Man festival experienced heavy rain, resulting in floods and muddy conditions. Thousands of attendees were stranded at the festival site in Nevada. There were false claims of an Ebola outbreak and a national emergency, but no emergency declaration was made. One death was reported at the festival, which is currently under investigation. Despite the challenging conditions, many festivalgoers remained unfazed and continued to enjoy the event. The exodus from the festival site began as the mud-caked desert started to dry up. Authorities issued a flash flood watch, and investigations are ongoing regarding the death at the festival.\u001b[0m\n",
|
||||
"\n",
|
||||
"\u001b[1m> Finished chain.\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'input': 'What happened in the latest burning man floods?',\n",
|
||||
" 'output': 'The latest Burning Man festival experienced heavy rain, resulting in floods and muddy conditions. Thousands of attendees were stranded at the festival site in Nevada. There were false claims of an Ebola outbreak and a national emergency, but no emergency declaration was made. One death was reported at the festival, which is currently under investigation. Despite the challenging conditions, many festivalgoers remained unfazed and continued to enjoy the event. The exodus from the festival site began as the mud-caked desert started to dry up. Authorities issued a flash flood watch, and investigations are ongoing regarding the death at the festival.'}"
|
||||
"AIMessage(content=\"The last women's singles champion at Wimbledon was Markéta Vondroušová, who won the title in 2023.\", response_metadata={'token_usage': {'completion_tokens': 26, 'prompt_tokens': 802, 'total_tokens': 828}, 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_4e2b2da518', 'finish_reason': 'stop', 'logprobs': None}, id='run-2bfeec6e-8f04-477e-bf51-9500f18bd514-0', usage_metadata={'input_tokens': 802, 'output_tokens': 26, 'total_tokens': 828})"
|
||||
]
|
||||
},
|
||||
"execution_count": 6,
|
||||
"execution_count": 23,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"agent_executor.invoke({\"input\": \"What happened in the latest burning man floods?\"})"
|
||||
"import datetime\n",
|
||||
"\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate\n",
|
||||
"from langchain_core.runnables import RunnableConfig, chain\n",
|
||||
"\n",
|
||||
"today = datetime.datetime.today().strftime(\"%D\")\n",
|
||||
"prompt = ChatPromptTemplate(\n",
|
||||
" [\n",
|
||||
" (\"system\", f\"You are a helpful assistant. The date today is {today}.\"),\n",
|
||||
" (\"human\", \"{user_input}\"),\n",
|
||||
" (\"placeholder\", \"{messages}\"),\n",
|
||||
" ]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# specifying tool_choice will force the model to call this tool.\n",
|
||||
"llm_with_tools = llm.bind_tools([tool])\n",
|
||||
"\n",
|
||||
"llm_chain = prompt | llm_with_tools\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@chain\n",
|
||||
"def tool_chain(user_input: str, config: RunnableConfig):\n",
|
||||
" input_ = {\"user_input\": user_input}\n",
|
||||
" ai_msg = llm_chain.invoke(input_, config=config)\n",
|
||||
" tool_msgs = tool.batch(ai_msg.tool_calls, config=config)\n",
|
||||
" return llm_chain.invoke({**input_, \"messages\": [ai_msg, *tool_msgs]}, config=config)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"tool_chain.invoke(\"who won the last womens singles wimbledon\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "86cd0a02",
|
||||
"cell_type": "markdown",
|
||||
"id": "fb115693-e89e-40f2-a460-0d0d39a17963",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
"source": [
|
||||
"Here's the [LangSmith trace](https://smith.langchain.com/public/b43232c1-b243-4a7f-afeb-5fba8c84ba56/r) for this run."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4ac8146c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## API reference\n",
|
||||
"\n",
|
||||
"For detailed documentation of all TavilySearchResults features and configurations head to the API reference: https://api.python.langchain.com/en/latest/tools/langchain_community.tools.tavily_search.tool.TavilySearchResults.html"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"display_name": "poetry-venv-311",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
"name": "poetry-venv-311"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
@ -234,7 +370,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.1"
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
@ -295,6 +295,10 @@ if TYPE_CHECKING:
|
||||
from langchain_community.tools.steamship_image_generation import (
|
||||
SteamshipImageGenerationTool,
|
||||
)
|
||||
from langchain_community.tools.tavily_search import (
|
||||
TavilyAnswer,
|
||||
TavilySearchResults,
|
||||
)
|
||||
from langchain_community.tools.vectorstore.tool import (
|
||||
VectorStoreQATool,
|
||||
VectorStoreQAWithSourcesTool,
|
||||
@ -450,6 +454,8 @@ __all__ = [
|
||||
"SteamWebAPIQueryRun",
|
||||
"SteamshipImageGenerationTool",
|
||||
"StructuredTool",
|
||||
"TavilyAnswer",
|
||||
"TavilySearchResults",
|
||||
"Tool",
|
||||
"VectorStoreQATool",
|
||||
"VectorStoreQAWithSourcesTool",
|
||||
@ -599,6 +605,8 @@ _module_lookup = {
|
||||
"SteamWebAPIQueryRun": "langchain_community.tools.steam.tool",
|
||||
"SteamshipImageGenerationTool": "langchain_community.tools.steamship_image_generation", # noqa: E501
|
||||
"StructuredTool": "langchain_core.tools",
|
||||
"TavilyAnswer": "langchain_community.tools.tavily_search",
|
||||
"TavilySearchResults": "langchain_community.tools.tavily_search",
|
||||
"Tool": "langchain_core.tools",
|
||||
"VectorStoreQATool": "langchain_community.tools.vectorstore.tool",
|
||||
"VectorStoreQAWithSourcesTool": "langchain_community.tools.vectorstore.tool",
|
||||
|
@ -26,7 +26,7 @@ class TavilySearchResults(BaseTool):
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pip install -U langchain-openai
|
||||
pip install -U langchain-community tavily-python
|
||||
export TAVILY_API_KEY="your-api-key"
|
||||
|
||||
Instantiate:
|
||||
@ -53,7 +53,7 @@ class TavilySearchResults(BaseTool):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
'{\n "answer": "Novak Djokovic won the last French Open by beating Casper Ruud ...',
|
||||
'{\n "url": "https://www.nytimes.com...", "content": "Novak Djokovic won the last French Open by beating Casper Ruud ...'
|
||||
|
||||
Invoke with tool call:
|
||||
|
||||
@ -64,7 +64,7 @@ class TavilySearchResults(BaseTool):
|
||||
.. code-block:: python
|
||||
|
||||
ToolMessage(
|
||||
content='{\n "answer": "Novak Djokovic won the last French Open by beating Casper Ruud ...',
|
||||
content='{\n "url": "https://www.nytimes.com...", "content": "Novak Djokovic won the last French Open by beating Casper Ruud ...',
|
||||
artifact={
|
||||
'query': 'who won the last french open',
|
||||
'follow_up_questions': None,
|
||||
@ -103,17 +103,45 @@ class TavilySearchResults(BaseTool):
|
||||
max_results: int = 5
|
||||
"""Max search results to return, default is 5"""
|
||||
search_depth: str = "advanced"
|
||||
'''The depth of the search. It can be "basic" or "advanced"'''
|
||||
"""The depth of the search. It can be "basic" or "advanced"
|
||||
|
||||
.. versionadded:: 0.2.5
|
||||
"""
|
||||
include_domains: List[str] = []
|
||||
"""A list of domains to specifically include in the search results. Default is None, which includes all domains.""" # noqa: E501
|
||||
"""A list of domains to specifically include in the search results.
|
||||
|
||||
Default is None, which includes all domains.
|
||||
|
||||
.. versionadded:: 0.2.5
|
||||
"""
|
||||
exclude_domains: List[str] = []
|
||||
"""A list of domains to specifically exclude from the search results. Default is None, which doesn't exclude any domains.""" # noqa: E501
|
||||
"""A list of domains to specifically exclude from the search results.
|
||||
|
||||
Default is None, which doesn't exclude any domains.
|
||||
|
||||
.. versionadded:: 0.2.5
|
||||
"""
|
||||
include_answer: bool = False
|
||||
"""Include a short answer to original query in the search results. Default is False.""" # noqa: E501
|
||||
"""Include a short answer to original query in the search results.
|
||||
|
||||
Default is False.
|
||||
|
||||
.. versionadded:: 0.2.5
|
||||
"""
|
||||
include_raw_content: bool = False
|
||||
"""Include cleaned and parsed HTML of each site search results. Default is False."""
|
||||
"""Include cleaned and parsed HTML of each site search results.
|
||||
|
||||
Default is False.
|
||||
|
||||
.. versionadded:: 0.2.5
|
||||
"""
|
||||
include_images: bool = False
|
||||
"""Include a list of query related images in the response. Default is False."""
|
||||
"""Include a list of query related images in the response.
|
||||
|
||||
Default is False.
|
||||
|
||||
.. versionadded:: 0.2.5
|
||||
"""
|
||||
|
||||
api_wrapper: TavilySearchAPIWrapper = Field(default_factory=TavilySearchAPIWrapper) # type: ignore[arg-type]
|
||||
response_format: Literal["content_and_artifact"] = "content_and_artifact"
|
||||
|
@ -124,6 +124,8 @@ EXPECTED_ALL = [
|
||||
"SteamWebAPIQueryRun",
|
||||
"SteamshipImageGenerationTool",
|
||||
"StructuredTool",
|
||||
"TavilyAnswer",
|
||||
"TavilySearchResults",
|
||||
"Tool",
|
||||
"VectorStoreQATool",
|
||||
"VectorStoreQAWithSourcesTool",
|
||||
|
@ -1,154 +0,0 @@
|
||||
"""Test the public API of the tools package."""
|
||||
|
||||
from langchain_community.tools import __all__ as public_api
|
||||
|
||||
_EXPECTED = [
|
||||
"AINAppOps",
|
||||
"AINOwnerOps",
|
||||
"AINRuleOps",
|
||||
"AINTransfer",
|
||||
"AINValueOps",
|
||||
"AIPluginTool",
|
||||
"APIOperation",
|
||||
"ArxivQueryRun",
|
||||
"AskNewsSearch",
|
||||
"AzureAiServicesDocumentIntelligenceTool",
|
||||
"AzureAiServicesImageAnalysisTool",
|
||||
"AzureAiServicesSpeechToTextTool",
|
||||
"AzureAiServicesTextToSpeechTool",
|
||||
"AzureAiServicesTextAnalyticsForHealthTool",
|
||||
"AzureCogsFormRecognizerTool",
|
||||
"AzureCogsImageAnalysisTool",
|
||||
"AzureCogsSpeech2TextTool",
|
||||
"AzureCogsText2SpeechTool",
|
||||
"AzureCogsTextAnalyticsHealthTool",
|
||||
"BaseGraphQLTool",
|
||||
"BaseRequestsTool",
|
||||
"BaseSQLDatabaseTool",
|
||||
"BaseSparkSQLTool",
|
||||
"BaseTool",
|
||||
"BearlyInterpreterTool",
|
||||
"BingSearchResults",
|
||||
"BingSearchRun",
|
||||
"BraveSearch",
|
||||
"ClickTool",
|
||||
"CogniswitchKnowledgeSourceFile",
|
||||
"CogniswitchKnowledgeStatus",
|
||||
"CogniswitchKnowledgeSourceURL",
|
||||
"CogniswitchKnowledgeRequest",
|
||||
"ConneryAction",
|
||||
"CopyFileTool",
|
||||
"CurrentWebPageTool",
|
||||
"DataheraldTextToSQL",
|
||||
"DeleteFileTool",
|
||||
"DuckDuckGoSearchResults",
|
||||
"DuckDuckGoSearchRun",
|
||||
"E2BDataAnalysisTool",
|
||||
"EdenAiExplicitImageTool",
|
||||
"EdenAiObjectDetectionTool",
|
||||
"EdenAiParsingIDTool",
|
||||
"EdenAiParsingInvoiceTool",
|
||||
"EdenAiSpeechToTextTool",
|
||||
"EdenAiTextModerationTool",
|
||||
"EdenAiTextToSpeechTool",
|
||||
"EdenaiTool",
|
||||
"ElevenLabsText2SpeechTool",
|
||||
"ExtractHyperlinksTool",
|
||||
"ExtractTextTool",
|
||||
"FileSearchTool",
|
||||
"GetElementsTool",
|
||||
"GmailCreateDraft",
|
||||
"GmailGetMessage",
|
||||
"GmailGetThread",
|
||||
"GmailSearch",
|
||||
"GmailSendMessage",
|
||||
"GoogleCloudTextToSpeechTool",
|
||||
"GooglePlacesTool",
|
||||
"GoogleSearchResults",
|
||||
"GoogleSearchRun",
|
||||
"GoogleSerperResults",
|
||||
"GoogleSerperRun",
|
||||
"HumanInputRun",
|
||||
"IFTTTWebhook",
|
||||
"InfoPowerBITool",
|
||||
"InfoSQLDatabaseTool",
|
||||
"InfoSparkSQLTool",
|
||||
"JiraAction",
|
||||
"JsonGetValueTool",
|
||||
"JsonListKeysTool",
|
||||
"ListDirectoryTool",
|
||||
"ListPowerBITool",
|
||||
"ListSQLDatabaseTool",
|
||||
"ListSparkSQLTool",
|
||||
"MerriamWebsterQueryRun",
|
||||
"MetaphorSearchResults",
|
||||
"MoveFileTool",
|
||||
"NasaAction",
|
||||
"NavigateBackTool",
|
||||
"NavigateTool",
|
||||
"O365CreateDraftMessage",
|
||||
"O365SearchEmails",
|
||||
"O365SearchEvents",
|
||||
"O365SendEvent",
|
||||
"O365SendMessage",
|
||||
"OpenAPISpec",
|
||||
"OpenWeatherMapQueryRun",
|
||||
"PubmedQueryRun",
|
||||
"PolygonAggregates",
|
||||
"PolygonFinancials",
|
||||
"PolygonLastQuote",
|
||||
"PolygonTickerNews",
|
||||
"RedditSearchRun",
|
||||
"RedditSearchSchema",
|
||||
"QueryCheckerTool",
|
||||
"QueryPowerBITool",
|
||||
"QuerySQLCheckerTool",
|
||||
"QuerySQLDataBaseTool",
|
||||
"QuerySparkSQLTool",
|
||||
"ReadFileTool",
|
||||
"RequestsDeleteTool",
|
||||
"RequestsGetTool",
|
||||
"RequestsPatchTool",
|
||||
"RequestsPostTool",
|
||||
"RequestsPutTool",
|
||||
"SceneXplainTool",
|
||||
"SearchAPIResults",
|
||||
"SearchAPIRun",
|
||||
"SearxSearchResults",
|
||||
"SearxSearchRun",
|
||||
"ShellTool",
|
||||
"SlackGetChannel",
|
||||
"SlackGetMessage",
|
||||
"SlackScheduleMessage",
|
||||
"SlackSendMessage",
|
||||
"SleepTool",
|
||||
"StdInInquireTool",
|
||||
"StackExchangeTool",
|
||||
"SteamshipImageGenerationTool",
|
||||
"StructuredTool",
|
||||
"SteamWebAPIQueryRun",
|
||||
"Tool",
|
||||
"VectorStoreQATool",
|
||||
"VectorStoreQAWithSourcesTool",
|
||||
"WikipediaQueryRun",
|
||||
"WolframAlphaQueryRun",
|
||||
"WriteFileTool",
|
||||
"YahooFinanceNewsTool",
|
||||
"YouSearchTool",
|
||||
"YouTubeSearchTool",
|
||||
"ZapierNLAListActions",
|
||||
"ZapierNLARunAction",
|
||||
"Detector",
|
||||
"ZenGuardInput",
|
||||
"ZenGuardTool",
|
||||
"authenticate",
|
||||
"format_tool_to_openai_function",
|
||||
"tool",
|
||||
"MojeekSearch",
|
||||
]
|
||||
|
||||
|
||||
def test_public_api() -> None:
|
||||
"""Test for regressions or changes in the public API."""
|
||||
# Check that the public API is as expected
|
||||
assert set(public_api) == set(_EXPECTED)
|
Loading…
Reference in New Issue
Block a user