docs: update tavily guides (#30387)

AgentExecutor -> langgraph
This commit is contained in:
ccurme 2025-03-19 19:29:57 -04:00 committed by GitHub
parent 4346aca5cf
commit aa5ac9279a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 93 additions and 145 deletions

View File

@ -1,6 +1,6 @@
# Tavily
[Tavily](https://tavily.com) Tavily is a search engine, specifically designed for AI agents.
[Tavily](https://tavily.com) 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. Tavilys primary mission is to provide factual
and reliable information from trusted sources, enhancing the accuracy and reliability of AI

File diff suppressed because one or more lines are too long

View File

@ -35,23 +35,10 @@
},
{
"cell_type": "code",
"execution_count": 1,
"id": "f85b4089",
"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"
]
}
],
"execution_count": null,
"id": "5536649f-e73d-42f2-8d57-80b7a790b7eb",
"metadata": {},
"outputs": [],
"source": [
"%pip install -qU langchain-tavily"
]
@ -238,7 +225,7 @@
"\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",
"In the below example when we ask the agent to find \"What nation hosted the Euro 2024? Include only wikipedia sources.\" the agent will dynamically set the argments and invoke Tavily search tool : Invoking `tavily_search` with `{'query': 'Euro 2024 host nation', 'include_domains': ['wikipedia.org']`\n",
"\n",
"import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
"\n",
@ -258,7 +245,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": 1,
"id": "af3123ad-7a02-40e5-b58e-7d56e23e5830",
"metadata": {},
"outputs": [],
@ -272,9 +259,27 @@
"llm = init_chat_model(model=\"gpt-4o\", model_provider=\"openai\", temperature=0)"
]
},
{
"cell_type": "markdown",
"id": "1020a506-473b-4e6a-a563-7aaf92c4d183",
"metadata": {},
"source": [
"We will need to install langgraph:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": null,
"id": "53ddaebb-dcd0-4e84-89c2-e9a85085f16b",
"metadata": {},
"outputs": [],
"source": [
"%pip install -qU langgraph"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "fdbf35b5-3aaf-4947-9ec6-48c21533fb95",
"metadata": {},
"outputs": [
@ -282,39 +287,29 @@
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"What nation hosted the Euro 2024? Include only wikipedia sources.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" tavily_search (call_yxmR4K2uadsQ8LKoyi8JyoLD)\n",
" Call ID: call_yxmR4K2uadsQ8LKoyi8JyoLD\n",
" Args:\n",
" query: Euro 2024 host nation\n",
" include_domains: ['wikipedia.org']\n",
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
"Name: tavily_search\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",
"{\"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 statistics Matches played 51 Goals scored 117 (2.29 per match) Attendance 2,681,288 (52,574 per match) Top scorer(s) Harry Kane Georges Mikautadze Jamal Musiala Cody Gakpo Ivan Schranz Dani Olmo (3 goals each) Best player(s) Rodri Best young player Lamine Yamal ← 2020 2028 → The 2024 UEFA European Football Championship, commonly referred to as UEFA Euro 2024 (stylised as UEFA EURO 2024) or simply Euro 2024, was the 17th UEFA European Championship, the quadrennial international football championship organised by UEFA for the European men's national teams of their member associations. Germany hosted the tournament, which took place from 14 June to 14 July 2024. The tournament involved 24 teams, with Georgia making their European Championship debut. [4] Host nation Germany were eliminated by Spain in the quarter-finals; Spain went on to win the tournament for a record fourth time after defeating England 21 in the final.\", \"score\": 0.9104262, \"raw_content\": null}, {\"title\": \"UEFA Euro 2024 - Simple English Wikipedia, the free encyclopedia\", \"url\": \"https://simple.wikipedia.org/wiki/UEFA_Euro_2024\", \"content\": \"The 2024 UEFA European Football Championship, also known as UEFA Euro 2024 or simply Euro 2024, was the 17th edition of the UEFA European Championship. Germany was hosting the tournament. ... The UEFA Executive Committee voted for the host in a secret ballot, with only a simple majority (more than half of the valid votes) required to determine\", \"score\": 0.81418616, \"raw_content\": null}, {\"title\": \"Championnat d'Europe de football 2024 — Wikipédia\", \"url\": \"https://fr.wikipedia.org/wiki/Championnat_d'Europe_de_football_2024\", \"content\": \"Le Championnat d'Europe de l'UEFA de football 2024 est la 17 e édition du Championnat d'Europe de football, communément abrégé en Euro 2024, compétition organisée par l'UEFA et rassemblant les meilleures équipes nationales masculines européennes. L'Allemagne est désignée pays organisateur de la compétition le 27 septembre 2018. C'est la troisième fois que des matches du Championnat\", \"score\": 0.8055255, \"raw_content\": null}, {\"title\": \"UEFA Euro 2024 bids - Wikipedia\", \"url\": \"https://en.wikipedia.org/wiki/UEFA_Euro_2024_bids\", \"content\": \"The bidding process of UEFA Euro 2024 ended on 27 September 2018 in Nyon, Switzerland, when Germany was announced to be the host. [1] Two bids came before the deadline, 3 March 2017, which were Germany and Turkey as single bids. ... Press agencies revealed on 24 October 2013, that the European football governing body UEFA would have decided on\", \"score\": 0.7882741, \"raw_content\": null}, {\"title\": \"2024 UEFA European Under-19 Championship - Wikipedia\", \"url\": \"https://en.wikipedia.org/wiki/2024_UEFA_European_Under-19_Championship\", \"content\": \"The 2024 UEFA European Under-19 Championship (also known as UEFA Under-19 Euro 2024) was the 21st edition of the UEFA European Under-19 Championship (71st edition if the Under-18 and Junior eras are included), the annual international youth football championship organised by UEFA for the men's under-19 national teams of Europe. Northern Ireland hosted the tournament from 15 to 28 July 2024.\", \"score\": 0.7783298, \"raw_content\": null}], \"response_time\": 1.67}\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\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"
"The nation that hosted Euro 2024 was Germany. You can find more information on the [Wikipedia page for UEFA Euro 2024](https://en.wikipedia.org/wiki/UEFA_Euro_2024).\n"
]
},
{
"data": {
"text/plain": [
"'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": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import datetime\n",
"\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",
"from langgraph.prebuilt import create_react_agent\n",
"\n",
"# Initialize Tavily Search Tool\n",
"tavily_search_tool = TavilySearch(\n",
@ -322,35 +317,15 @@
" topic=\"general\",\n",
")\n",
"\n",
"# Set up Prompt with 'agent_scratchpad'\n",
"today = datetime.datetime.today().strftime(\"%D\")\n",
"prompt = ChatPromptTemplate.from_messages(\n",
" [\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",
"agent = create_react_agent(llm, [tavily_search_tool])\n",
"\n",
"# Create an agent that can use tools\n",
"agent = create_openai_tools_agent(llm=llm, tools=[tavily_search_tool], prompt=prompt)\n",
"user_input = \"What nation hosted the Euro 2024? Include only wikipedia sources.\"\n",
"\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",
"# Construct input properly as a dictionary\n",
"response = agent_executor.invoke({\"messages\": [HumanMessage(content=user_input)]})\n",
"response[\"output\"]"
"for step in agent.stream(\n",
" {\"messages\": user_input},\n",
" stream_mode=\"values\",\n",
"):\n",
" step[\"messages\"][-1].pretty_print()"
]
},
{
@ -366,7 +341,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@ -380,7 +355,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
"version": "3.10.4"
}
},
"nbformat": 4,