mirror of
https://github.com/hwchase17/langchain.git
synced 2025-06-21 14:18:52 +00:00
Integration update (#30381)
This pull request includes a change to the following - docs/docs/integrations/tools/tavily_search.ipynb - docs/docs/integrations/tools/tavily_extract.ipynb - added docs/docs/integrations/providers/tavily.mdx --------- Co-authored-by: pulvedu <dustin@tavily.com>
This commit is contained in:
parent
9b687d7fbd
commit
4346aca5cf
17
docs/docs/integrations/providers/tavily.mdx
Normal file
17
docs/docs/integrations/providers/tavily.mdx
Normal file
@ -0,0 +1,17 @@
|
||||
# Tavily
|
||||
|
||||
[Tavily](https://tavily.com) Tavily is a search engine, specifically designed for AI agents.
|
||||
Tavily provides both a search and extract API, AI developers can effortlessly integrate their
|
||||
applications with realtime online information. Tavily’s primary mission is to provide factual
|
||||
and reliable information from trusted sources, enhancing the accuracy and reliability of AI
|
||||
generated content and reasoning.
|
||||
|
||||
## Installation and Setup
|
||||
|
||||
```bash
|
||||
pip install langchain-tavily
|
||||
```
|
||||
|
||||
## Tools
|
||||
|
||||
See detail on available tools [tavily_search](/docs/integrations/tools/tavily_search) and [tavily_extract](/docs/integrations/tools/tavily_extract).
|
375
docs/docs/integrations/tools/tavily_extract.ipynb
Normal file
375
docs/docs/integrations/tools/tavily_extract.ipynb
Normal file
File diff suppressed because one or more lines are too long
@ -18,29 +18,42 @@
|
||||
"## Overview\n",
|
||||
"\n",
|
||||
"### Integration details\n",
|
||||
"| Class | Package | Serializable | [JS support](https://js.langchain.com/docs/integrations/tools/tavily_search) | Package latest |\n",
|
||||
"| :--- | :--- | :---: | :---: | :---: |\n",
|
||||
"| [TavilySearchResults](https://python.langchain.com/api_reference/community/tools/langchain_community.tools.tavily_search.tool.TavilySearchResults.html) | [langchain-community](https://python.langchain.com/api_reference/community/index.html) | ❌ | ✅ |  |\n",
|
||||
"| Class | Package | Serializable | [JS support](https://js.langchain.com/docs/integrations/tools/tavily_search) | Package latest |\n",
|
||||
"|:--------------------------------------------------------------|:---------------------------------------------------------------| :---: | :---: | :---: |\n",
|
||||
"| [TavilySearch](https://github.com/tavily-ai/langchain-tavily) | [langchain-tavily](https://pypi.org/project/langchain-tavily/) | ❌ | ❌ |  |\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",
|
||||
"| [Returns artifact](/docs/how_to/tool_artifacts/) | Native async | Return data | Pricing |\n",
|
||||
"| :---: | :---: |:--------------------------------------------------------:| :---: |\n",
|
||||
"| ❌ | ✅ | title, URL, content snippet, raw_content, answer, images | 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."
|
||||
"The integration lives in the `langchain-tavily` package."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 1,
|
||||
"id": "f85b4089",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2025-03-19T16:45:22.942913Z",
|
||||
"start_time": "2025-03-19T16:45:22.799418Z"
|
||||
}
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Note: you may need to restart the kernel to use updated packages.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"%pip install -qU \"langchain-community>=0.2.11\" tavily-python"
|
||||
"%pip install -qU langchain-tavily"
|
||||
]
|
||||
},
|
||||
{
|
||||
@ -57,7 +70,12 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "e0b178a2-8816-40ca-b57c-ccdd86dde9c9",
|
||||
"metadata": {},
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2025-03-19T16:43:32.810957Z",
|
||||
"start_time": "2025-03-19T16:43:15.570Z"
|
||||
}
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import getpass\n",
|
||||
@ -67,25 +85,6 @@
|
||||
" os.environ[\"TAVILY_API_KEY\"] = getpass.getpass(\"Tavily API key:\\n\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"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:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "a6c2f136-6367-4f1f-825d-ae741e1bf281",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# os.environ[\"LANGSMITH_TRACING\"] = \"true\"\n",
|
||||
"# os.environ[\"LANGSMITH_API_KEY\"] = getpass.getpass()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1c97218f-f366-479d-8bf7-fe9f2f6df73f",
|
||||
@ -93,29 +92,34 @@
|
||||
"source": [
|
||||
"## Instantiation\n",
|
||||
"\n",
|
||||
"Here we show how to instantiate an instance of the Tavily search tools, with "
|
||||
"Here we show how to instantiate an instance of the Tavily search tools, with"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"execution_count": 3,
|
||||
"id": "8b3ddfe9-ca79-494c-a7ab-1f56d9407a64",
|
||||
"metadata": {},
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2025-03-19T16:44:04.570451Z",
|
||||
"start_time": "2025-03-19T16:44:04.561713Z"
|
||||
}
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain_community.tools import TavilySearchResults\n",
|
||||
"from langchain_tavily import TavilySearch\n",
|
||||
"\n",
|
||||
"tool = TavilySearchResults(\n",
|
||||
"tool = TavilySearch(\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",
|
||||
" topic=\"general\",\n",
|
||||
" # include_answer=False,\n",
|
||||
" # include_raw_content=False,\n",
|
||||
" # include_images=False,\n",
|
||||
" # include_image_descriptions=False,\n",
|
||||
" # search_depth=\"basic\",\n",
|
||||
" # time_range=\"day\",\n",
|
||||
" # include_domains=None,\n",
|
||||
" # exclude_domains=None\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
@ -128,31 +132,57 @@
|
||||
"\n",
|
||||
"### [Invoke directly with args](/docs/concepts/tools)\n",
|
||||
"\n",
|
||||
"The `TavilySearchResults` tool takes a single \"query\" argument, which should be a natural language query:"
|
||||
"The Tavily search tool accepts the following arguments during invocation:\n",
|
||||
"- `query` (required): A natural language search query\n",
|
||||
"- The following arguments can also be set during invokation : `include_images`, `search_depth` , `time_range`, `include_domains`, `exclude_domains`, `include_images`\n",
|
||||
"- For reliability and performance reasons, certain parameters that affect response size cannot be modified during invocation: `include_answer` and `include_raw_content`. These limitations prevent unexpected context window issues and ensure consistent results.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"NOTE: The optional arguments are available for agents to dynamically set, if you set a argument during instantiation and then invoke the tool with a different value, the tool will use the value you passed during invokation."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": 4,
|
||||
"id": "65310a8b-eb0c-4d9e-a618-4f4abe2414fc",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[{'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 ...\"}]"
|
||||
"{'query': 'What happened at the last wimbledon',\n",
|
||||
" 'follow_up_questions': None,\n",
|
||||
" 'answer': None,\n",
|
||||
" 'images': [],\n",
|
||||
" 'results': [{'title': \"Andy Murray pulls out of the men's singles draw at his last Wimbledon\",\n",
|
||||
" 'url': 'https://www.nbcnews.com/news/sports/andy-murray-wimbledon-tennis-singles-draw-rcna159912',\n",
|
||||
" 'content': \"NBC News Now LONDON — Andy Murray, one of the last decade's most successful male tennis players, has pulled out of the singles tournament at what is almost certain to be his last Wimbledon, his team confirmed Tuesday. Murray, 37, who has won the Wimbledon singles title twice and the U.S Open once, has been battling to be fit to play at the All England Club for weeks. “Unfortunately, despite working incredibly hard on his recovery since his operation just over a week ago, Andy has taken the very difficult decision not to play the singles this year,” his team said in a statement reported by Sky News. The news caps a glittering career on the ATP singles tour, which placed Murray at No. 1 in the world for 41 weeks.\",\n",
|
||||
" 'score': 0.67527276,\n",
|
||||
" 'raw_content': None},\n",
|
||||
" {'title': 'Andy Murray brought to tears by emotional ceremony as Wimbledon ...',\n",
|
||||
" 'url': 'https://edition.cnn.com/2024/07/05/sport/andy-murray-wimbledon-farewell-ceremony-spt-intl/index.html',\n",
|
||||
" 'content': 'Andy Murray brought to tears by emotional ceremony as Wimbledon farewell begins with doubles defeat | CNN Football Tennis Golf Motorsport US Sports Olympics Climbing Esports Hockey CNN10 About CNN Andy Murray became emotional when speaking on court following his Wimbledon defeat on Thursday. 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. Following a doubles defeat alongside his brother Jamie on Thursday, Murray was moved to tears after a short ceremony on Centre Court in which a montage of his career played out on big screens. Murray watches on as a video montage of his career highlights plays on the big screens at Wimbledon. CNN10 About CNN',\n",
|
||||
" 'score': 0.43482184,\n",
|
||||
" 'raw_content': None},\n",
|
||||
" {'title': 'Wimbledon - Latest News, Headlines and Entertainment from the BBC',\n",
|
||||
" 'url': 'https://www.bbc.co.uk/news/topics/c1kr68g26j9t',\n",
|
||||
" 'content': \"Wimbledon - Latest News, Headlines and Entertainment from the BBC BBC Homepage Search BBC Close menu BBC News BBC Verify World News TV Weather for Wimbledon London London Disabled people share experience of accessible homes London Man's pop-up urinal death may never be explained, family fears London London London London London London London Met PC jailed for assaulting man in hospital bed London London London Man jumped to his death in police station - inquest London Central London YMCA closes after failed injunction Kerr denies 'whiteness as insult' against police Man denies being getaway driver in £1m watch raid About the BBC Contact the BBC BBC emails for you The BBC is not responsible for the content of external sites.\",\n",
|
||||
" 'score': 0.3916624,\n",
|
||||
" 'raw_content': None},\n",
|
||||
" {'title': 'Wimbledon - latest news, breaking stories and comment - The Independent',\n",
|
||||
" 'url': 'https://www.independent.co.uk/topic/wimbledon',\n",
|
||||
" 'content': \"Independent Australian Open champion Jannik Sinner's style draws comparisons to Novak Djokovic Patten wins second grand slam doubles title after Australian Open epic Australian Open: Madison Keys can win her first Slam title and stop Aryna Sabalenka's threepeat Novak Djokovic hits back to beat Carlos Alcaraz in Australian Open thriller Australian Open 2025: Carlos Alcaraz and Jannik Sinner have a real rivalry atop men's tennis Australian Open 2025: Carlos Alcaraz and Jannik Sinner have a real rivalry atop men's tennis Australian Open 2025: Cases involving Jannik Sinner and Iga Swiatek make doping a top topic Australian Open 2025: There really isn't much time off in the offseason for tennis players Jd Sports Discount Code\",\n",
|
||||
" 'score': 0.3539422,\n",
|
||||
" 'raw_content': None},\n",
|
||||
" {'title': 'Novak Djokovic loses to Carlos Alcaraz Wimbledon final',\n",
|
||||
" 'url': 'https://www.wimbledon.com/en_GB/news/articles/2023-07-16/alcaraz_ends_the_djokovic_run.html',\n",
|
||||
" 'content': 'Password* By joining myWimbledon you are confirming you are happy to receive news and information from The All England Lawn Tennis Club regarding The Club, The Championships and The Grounds via email By joining myWimbledon you are confirming you are happy to receive news and information from The All England Lawn Tennis Club regarding The Club, The Championships and The Grounds via email Please enter your email address to update your password: We have sent details on how to update your password to the email address you provided. A verification email with a link to verify your account has been sent to you. Please enter the code sent to your email address below and click SUBMIT to complete the verification.',\n",
|
||||
" 'score': 0.23453853,\n",
|
||||
" 'raw_content': None}],\n",
|
||||
" 'response_time': 1.43}"
|
||||
]
|
||||
},
|
||||
"execution_count": 2,
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
@ -181,7 +211,7 @@
|
||||
"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"
|
||||
"{\"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\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@ -199,69 +229,16 @@
|
||||
"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",
|
||||
"## Use within an agent\n",
|
||||
"\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",
|
||||
"We can use our tools directly with an agent executor by binding the tool to the agent. This gives the agent the ability to dynamically set the available arguments to the Tavily search tool.\n",
|
||||
"\n",
|
||||
"In the below example when we ask the agent to find \"What is the most popular sport in the world? include only wikipedia sources\" the agent will dynamically set the argments and invoke Tavily search tool : Invoking `tavily_search` with `{'query': 'most popular sport in the world', 'include_domains': ['wikipedia.org']`\n",
|
||||
"\n",
|
||||
"import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
|
||||
"\n",
|
||||
@ -270,7 +247,18 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 10,
|
||||
"id": "b14d41f2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"if not os.environ.get(\"OPENAI_API_KEY\"):\n",
|
||||
" os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OPENAI_API_KEY:\\n\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"id": "af3123ad-7a02-40e5-b58e-7d56e23e5830",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@ -286,17 +274,33 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 23,
|
||||
"execution_count": 15,
|
||||
"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` with `{'query': 'most popular sport in the world', 'include_domains': ['wikipedia.org']}`\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\u001b[0m\u001b[36;1m\u001b[1;3m{'query': 'most popular sport in the world', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Sport - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/Sport', 'content': 'The world\\'s most accessible and practised sport is running, while association football is the most popular spectator sport. [7] Meaning and usage. Etymology. The word \"sport\" comes from the Old French desport meaning \"leisure\", with the oldest definition in English from around 1300 being \"anything humans find amusing or entertaining\". [8]', 'score': 0.69746524, 'raw_content': None}, {'title': 'List of sports - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/List_of_sports', 'content': \"According to the World Sports Encyclopaedia (2003), there are 8,000 known indigenous sports and sporting games. [1] Acrobatic arts Cheerleading. Breakdancing ... If just 2% of our most loyal readers gave $2.75 today, we'd hit our goal in a few hours. Most readers don't donate, so if Wikipedia has given you $2.75 worth of knowledge, please give\", 'score': 0.59344494, 'raw_content': None}, {'title': 'List of association football attendance records - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/List_of_association_football_attendance_records', 'content': 'Association football, more commonly known as \"football\" or \"soccer\" is the most popular sport at 3.5 billion fans. [1] [2] ... Uruguay v Brazil in the 1950 FIFA World Cup was officially spectated by 173,850 people but also determines there may have been closer to 200,000.', 'score': 0.5820878, 'raw_content': None}, {'title': 'Sports in the United States - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/Sports_in_the_United_States', 'content': \"Sports in the United States are an important part of the nation's culture.Historically, the most popular sport has been baseball.However, in more recent decades, American football has been the most popular spectator sport based on broadcast viewership audience. Basketball has grown into the mainstream American sports scene since the 1980s, with ice hockey and soccer doing the same around the\", 'score': 0.5565207, 'raw_content': None}, {'title': 'Western sports - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/Western_sports', 'content': 'A depiction of the FIFA World Cup, the most popular sporting event in the world.. Western sports are sports that are strongly associated with the West. [a] Many modern sports were invented in or standardized by Western countries; [1] in particular, many major sports were invented in the United Kingdom after the Industrial Revolution, [2] [3] and later, America invented some major sports such', 'score': 0.52700067, 'raw_content': None}], 'response_time': 1.55}\u001b[0m\u001b[32;1m\u001b[1;3mThe most popular sport in the world is association football, commonly known as \"football\" or \"soccer,\" with approximately 3.5 billion fans. You can find more information on this topic on [Wikipedia](https://en.wikipedia.org/wiki/List_of_association_football_attendance_records).\u001b[0m\n",
|
||||
"\n",
|
||||
"\u001b[1m> Finished chain.\u001b[0m\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"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})"
|
||||
"'The most popular sport in the world is association football, commonly known as \"football\" or \"soccer,\" with approximately 3.5 billion fans. You can find more information on this topic on [Wikipedia](https://en.wikipedia.org/wiki/List_of_association_football_attendance_records).'"
|
||||
]
|
||||
},
|
||||
"execution_count": 23,
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
@ -304,41 +308,49 @@
|
||||
"source": [
|
||||
"import datetime\n",
|
||||
"\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate\n",
|
||||
"from langchain_core.runnables import RunnableConfig, chain\n",
|
||||
"from langchain.agents import AgentExecutor, create_openai_tools_agent\n",
|
||||
"from langchain.schema import HumanMessage\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
|
||||
"from langchain_tavily import TavilySearch\n",
|
||||
"\n",
|
||||
"# Initialize LLM\n",
|
||||
"llm = init_chat_model(model=\"gpt-4o\", model_provider=\"openai\", temperature=0)\n",
|
||||
"\n",
|
||||
"# Initialize Tavily Search Tool\n",
|
||||
"tavily_search_tool = TavilySearch(\n",
|
||||
" max_results=5,\n",
|
||||
" topic=\"general\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Set up Prompt with 'agent_scratchpad'\n",
|
||||
"today = datetime.datetime.today().strftime(\"%D\")\n",
|
||||
"prompt = ChatPromptTemplate(\n",
|
||||
"prompt = ChatPromptTemplate.from_messages(\n",
|
||||
" [\n",
|
||||
" (\"system\", f\"You are a helpful assistant. The date today is {today}.\"),\n",
|
||||
" (\"human\", \"{user_input}\"),\n",
|
||||
" (\"placeholder\", \"{messages}\"),\n",
|
||||
" (\n",
|
||||
" \"system\",\n",
|
||||
" f\"\"\"You are a helpful reaserch assistant, you will be given a query and you will need to \n",
|
||||
" search the web for the most relevant information. The date today is {today}.\"\"\",\n",
|
||||
" ),\n",
|
||||
" MessagesPlaceholder(variable_name=\"messages\"),\n",
|
||||
" MessagesPlaceholder(\n",
|
||||
" variable_name=\"agent_scratchpad\"\n",
|
||||
" ), # Required for tool calls\n",
|
||||
" ]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# specifying tool_choice will force the model to call this tool.\n",
|
||||
"llm_with_tools = llm.bind_tools([tool])\n",
|
||||
"# Create an agent that can use tools\n",
|
||||
"agent = create_openai_tools_agent(llm=llm, tools=[tavily_search_tool], prompt=prompt)\n",
|
||||
"\n",
|
||||
"llm_chain = prompt | llm_with_tools\n",
|
||||
"# Create an Agent Executor to handle tool execution\n",
|
||||
"agent_executor = AgentExecutor(agent=agent, tools=[tavily_search_tool], verbose=True)\n",
|
||||
"\n",
|
||||
"user_input = (\n",
|
||||
" \"What is the most popular sport in the world? include only wikipedia sources\"\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": "markdown",
|
||||
"id": "fb115693-e89e-40f2-a460-0d0d39a17963",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here's the [LangSmith trace](https://smith.langchain.com/public/b43232c1-b243-4a7f-afeb-5fba8c84ba56/r) for this run."
|
||||
"# Construct input properly as a dictionary\n",
|
||||
"response = agent_executor.invoke({\"messages\": [HumanMessage(content=user_input)]})\n",
|
||||
"response[\"output\"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
@ -348,15 +360,15 @@
|
||||
"source": [
|
||||
"## API reference\n",
|
||||
"\n",
|
||||
"For detailed documentation of all TavilySearchResults features and configurations head to the API reference: https://python.langchain.com/api_reference/community/tools/langchain_community.tools.tavily_search.tool.TavilySearchResults.html"
|
||||
"For detailed documentation of all Tavily Search API features and configurations head to the API reference: https://docs.tavily.com/documentation/api-reference/endpoint/search"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "poetry-venv-311",
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "poetry-venv-311"
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
|
@ -524,3 +524,6 @@ packages:
|
||||
path: .
|
||||
repo: dell/powerscale-rag-connector
|
||||
provider_page: dell
|
||||
- name: langchain-tavily
|
||||
path: .
|
||||
repo: tavily-ai/langchain-tavily
|
Loading…
Reference in New Issue
Block a user