docs: Get rid of ZeroShotAgent and use create_react_agent instead (#20155)

- **Issue:** #20122
- @baskaryan,@eyurtsev
pull/20119/head^2
Guangdong Liu 3 months ago committed by GitHub
parent 2238490069
commit 1e3b07aae2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -24,31 +24,46 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"id": "8db95912",
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:19:07.167371Z",
"start_time": "2024-04-17T15:19:06.179726Z"
},
"pycharm": {
"is_executing": true
}
},
"outputs": [],
"source": [
"from langchain.agents import AgentExecutor, Tool, ZeroShotAgent\n",
"from langchain.chains import LLMChain\n",
"from langchain.memory import ConversationBufferMemory\n",
"import os\n",
"\n",
"from langchain import hub\n",
"from langchain.agents import AgentExecutor, Tool\n",
"from langchain_community.chat_message_histories import RedisChatMessageHistory\n",
"from langchain_community.utilities import GoogleSearchAPIWrapper\n",
"from langchain_community.utilities import SerpAPIWrapper\n",
"from langchain_core.runnables.history import RunnableWithMessageHistory\n",
"from langchain_openai import OpenAI"
]
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 2,
"id": "97ad8467",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:19:08.240386Z",
"start_time": "2024-04-17T15:19:08.233094Z"
}
},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper()\n",
"os.environ[\"GOOGLE_API_KEY\"] = \"GOOGLE_API_KEY\"\n",
"os.environ[\"GOOGLE_CSE_ID\"] = \"GOOGLE_CSE_ID\"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"OPENAI_API_KEY\"\n",
"\n",
"search = SerpAPIWrapper()\n",
"tools = [\n",
" Tool(\n",
" name=\"Search\",\n",
@ -68,24 +83,17 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 6,
"id": "e3439cd6",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:19:21.515150Z",
"start_time": "2024-04-17T15:19:15.549110Z"
}
},
"outputs": [],
"source": [
"prefix = \"\"\"Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:\"\"\"\n",
"suffix = \"\"\"Begin!\"\n",
"\n",
"{chat_history}\n",
"Question: {input}\n",
"{agent_scratchpad}\"\"\"\n",
"\n",
"prompt = ZeroShotAgent.create_prompt(\n",
" tools,\n",
" prefix=prefix,\n",
" suffix=suffix,\n",
" input_variables=[\"input\", \"chat_history\", \"agent_scratchpad\"],\n",
")"
"prompt = hub.pull(\"hwchase17/react\")"
]
},
{
@ -98,17 +106,18 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 7,
"id": "17638dc7",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:19:26.689119Z",
"start_time": "2024-04-17T15:19:26.442469Z"
}
},
"outputs": [],
"source": [
"message_history = RedisChatMessageHistory(\n",
" url=\"redis://localhost:6379/0\", ttl=600, session_id=\"my-session\"\n",
")\n",
"\n",
"memory = ConversationBufferMemory(\n",
" memory_key=\"chat_history\", chat_memory=message_history\n",
" url=\"redis://127.0.0.1:6379/0\", ttl=600, session_id=\"my-session\"\n",
")"
]
},
@ -122,23 +131,33 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 8,
"id": "c56a0e73",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:19:29.158350Z",
"start_time": "2024-04-17T15:19:29.090646Z"
}
},
"outputs": [],
"source": [
"llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)\n",
"agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)\n",
"agent_chain = AgentExecutor.from_agent_and_tools(\n",
" agent=agent, tools=tools, verbose=True, memory=memory\n",
")"
"from langchain.agents import create_react_agent\n",
"\n",
"model = OpenAI()\n",
"agent = create_react_agent(model, tools, prompt)\n",
"agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 12,
"id": "ca4bc1fb",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:20:27.186923Z",
"start_time": "2024-04-17T15:19:51.742185Z"
}
},
"outputs": [
{
"name": "stdout",
@ -146,29 +165,38 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I should use the Search tool to find the latest population data for Canada.\n",
"Action: Search\n",
"Action Input: Population of Canada\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada's Population and Demography Portal. Population of Canada (real- ... Index to the latest information from the Census of Population. This survey conducted by Statistics Canada provides a statistical portrait of Canada and its ... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. The 2021 Canadian census counted a total population of 36,991,981, an increase of around 5.2 percent over the 2016 figure. ... Between 1990 and 2008, the ... ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations ... Canada is a country in North America. Its ten provinces and three territories extend from ... Population. • Q4 2022 estimate. 39,292,355 (37th). Information is available for the total Indigenous population and each of the three ... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun 14, 2022 ... Determinants of health are the broad range of personal, social, economic and environmental factors that determine individual and population ... COVID-19 vaccination coverage across Canada by demographics and key populations. Updated every Friday at 12:00 PM Eastern Time.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\n",
"\u001b[1m> Finished AgentExecutor chain.\u001b[0m\n"
"Action Input: \"population of canada\"\u001B[0m\u001B[36;1m\u001B[1;3m{'type': 'population_result', 'place': 'Canada', 'population': '38.93 million', 'year': '2022'}\u001B[0m\u001B[32;1m\u001B[1;3mI now know the final answer\n",
"Final Answer: The final answer to the original input question is 38.93 million people live in Canada as of 2022.\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n"
]
},
{
"data": {
"text/plain": [
"'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'"
]
"text/plain": "{'input': 'How many people live in canada?',\n 'chat_history': [],\n 'output': 'The final answer to the original input question is 38.93 million people live in Canada as of 2022.'}"
},
"execution_count": 16,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_chain.run(input=\"How many people live in canada?\")"
"agent_with_chat_history = RunnableWithMessageHistory(\n",
" agent_executor,\n",
" # This is needed because in most real world scenarios, a session id is needed\n",
" # It isn't really used here because we are using a simple in memory ChatMessageHistory\n",
" lambda session_id: message_history,\n",
" input_messages_key=\"input\",\n",
" history_messages_key=\"chat_history\",\n",
")\n",
"\n",
"agent_with_chat_history.invoke(\n",
" {\"input\": \"How many people live in canada?\"},\n",
" config={\"configurable\": {\"session_id\": \"<foo>\"}},\n",
")"
]
},
{
@ -181,9 +209,14 @@
},
{
"cell_type": "code",
"execution_count": 17,
"execution_count": 13,
"id": "eecc0462",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:20:59.141583Z",
"start_time": "2024-04-17T15:20:47.717981Z"
}
},
"outputs": [
{
"name": "stdout",
@ -191,29 +224,29 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out what the national anthem of Canada is called.\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m There are many countries in the world with different national anthems, so I may need to specify which country's national anthem I am looking for.\n",
"Action: Search\n",
"Action Input: National Anthem of Canada\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mJun 7, 2010 ... https://twitter.com/CanadaImmigrantCanadian National Anthem O Canada in HQ - complete with lyrics, captions, vocals & music.LYRICS:O Canada! Nov 23, 2022 ... After 100 years of tradition, O Canada was proclaimed Canada's national anthem in 1980. The music for O Canada was composed in 1880 by Calixa ... O Canada, national anthem of Canada. It was proclaimed the official national anthem on July 1, 1980. “God Save the Queen” remains the royal anthem of Canada ... O Canada! Our home and native land! True patriot love in all of us command. Car ton bras sait porter l'épée,. Il sait porter la croix! \"O Canada\" (French: Ô Canada) is the national anthem of Canada. The song was originally commissioned by Lieutenant Governor of Quebec Théodore Robitaille ... Feb 1, 2018 ... It was a simple tweak — just two words. But with that, Canada just voted to make its national anthem, “O Canada,” gender neutral, ... \"O Canada\" was proclaimed Canada's national anthem on July 1,. 1980, 100 years after it was first sung on June 24, 1880. The music. Patriotic music in Canada dates back over 200 years as a distinct category from British or French patriotism, preceding the first legal steps to ... Feb 4, 2022 ... English version: O Canada! Our home and native land! True patriot love in all of us command. With glowing hearts we ... Feb 1, 2018 ... Canada's Senate has passed a bill making the country's national anthem gender-neutral. If you're not familiar with the words to “O Canada,” ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
"Final Answer: The national anthem of Canada is called \"O Canada\".\u001b[0m\n",
"\u001b[1m> Finished AgentExecutor chain.\u001b[0m\n"
"Action Input: \"national anthem\" + country name\u001B[0m\u001B[36;1m\u001B[1;3m['\"Liberté\" (\"Freedom\") · \"Esta É a Nossa Pátria Bem Amada\" (\"This Is Our Beloved Country\") · \"Dear Land of Guyana, of Rivers and Plains\" · \"La Dessalinienne\" (\"Song ...', 'National Anthem of Every Country ; Fiji, “Meda Dau Doka” (“God Bless Fiji”) ; Finland, “Maamme”. (“Our Land”) ; France, “La Marseillaise” (“The Marseillaise”).', 'List of national anthems ; Albania · Hymni i Flamurit · Algeria ; The Bahamas · March On, Bahamaland · Bahrain ; Cambodia · Nokoreach · Cameroon ; Madagascar · Ry ...', 'General information: Hatikvah (the Hope) is now firmly established as the Anthem of the State of Israel as well as the Jewish National Anthem. 1. While yet ...', 'National anthem · Afghanistan · Akrotiri · Albania · Algeria · American Samoa · Andorra · Angola · Anguilla.', 'Background > National anthems: Countries Compared ; DjiboutiDjibouti, Djibouti ; DominicaDominica, Isle of Beauty, Isle of Splendour ; Dominican RepublicDominican ...', \"Today, the total number is massive, with all 193 UN countries having a national anthem. Former and non-UN countries' anthems add to the list. Due to space ...\", '1. United States of America - The Star-Spangled Banner · 2. United Kingdom - God Save the Queen/King · 3. Canada - O Canada · 4. France - La ...', \"Pedro I wrote the song that was used as the national anthem of Brazil from 1822 to 1831. The song is now recognized as the country's official patriotic song. 7.\"]\u001B[0m\u001B[32;1m\u001B[1;3mI now know the final answer\n",
"Final Answer: The final answer cannot be determined without specifying which country's national anthem is being referred to.\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n"
]
},
{
"data": {
"text/plain": [
"'The national anthem of Canada is called \"O Canada\".'"
]
"text/plain": "{'input': 'what is their national anthem called?',\n 'chat_history': [HumanMessage(content='How many people live in canada?'),\n AIMessage(content='The final answer to the original input question is 38.93 million people live in Canada as of 2022.')],\n 'output': \"The final answer cannot be determined without specifying which country's national anthem is being referred to.\"}"
},
"execution_count": 17,
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_chain.run(input=\"what is their national anthem called?\")"
"agent_with_chat_history.invoke(\n",
" {\"input\": \"what is their national anthem called?\"},\n",
" config={\"configurable\": {\"session_id\": \"<foo>\"}},\n",
")"
]
},
{
@ -228,32 +261,30 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 14,
"id": "3359d043",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:21:12.756721Z",
"start_time": "2024-04-17T15:21:12.745830Z"
}
},
"outputs": [],
"source": [
"prefix = \"\"\"Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:\"\"\"\n",
"suffix = \"\"\"Begin!\"\n",
"\n",
"Question: {input}\n",
"{agent_scratchpad}\"\"\"\n",
"\n",
"prompt = ZeroShotAgent.create_prompt(\n",
" tools, prefix=prefix, suffix=suffix, input_variables=[\"input\", \"agent_scratchpad\"]\n",
")\n",
"llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)\n",
"agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)\n",
"agent_without_memory = AgentExecutor.from_agent_and_tools(\n",
" agent=agent, tools=tools, verbose=True\n",
")"
"agent = create_react_agent(model, tools, prompt)\n",
"agent_executor__without_memory = AgentExecutor(agent=agent, tools=tools, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"execution_count": 21,
"id": "970d23df",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:23:37.774243Z",
"start_time": "2024-04-17T15:23:29.655034Z"
}
},
"outputs": [
{
"name": "stdout",
@ -261,36 +292,38 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m To find the number of people living in Canada, I should use a search engine to look for a reliable source.\n",
"Action: Search\n",
"Action Input: Population of Canada\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada's Population and Demography Portal. Population of Canada (real- ... Index to the latest information from the Census of Population. This survey conducted by Statistics Canada provides a statistical portrait of Canada and its ... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. The 2021 Canadian census counted a total population of 36,991,981, an increase of around 5.2 percent over the 2016 figure. ... Between 1990 and 2008, the ... ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations ... Canada is a country in North America. Its ten provinces and three territories extend from ... Population. • Q4 2022 estimate. 39,292,355 (37th). Information is available for the total Indigenous population and each of the three ... The term 'Aboriginal' or 'Indigenous' used on the Statistics Canada ... Jun 14, 2022 ... Determinants of health are the broad range of personal, social, economic and environmental factors that determine individual and population ... COVID-19 vaccination coverage across Canada by demographics and key populations. Updated every Friday at 12:00 PM Eastern Time.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.\u001b[0m\n",
"\u001b[1m> Finished AgentExecutor chain.\u001b[0m\n"
"Action Input: \"Population of Canada\"\u001B[0m\u001B[36;1m\u001B[1;3m{'type': 'population_result', 'place': 'Canada', 'population': '38.93 million', 'year': '2022'}\u001B[0m\u001B[32;1m\u001B[1;3m38.93 million people live in Canada as of 2022.\n",
"Final Answer: 38.93 million people live in Canada.\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n"
]
},
{
"data": {
"text/plain": [
"'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'"
]
"text/plain": "{'input': 'How many people live in canada?',\n 'output': '38.93 million people live in Canada.'}"
},
"execution_count": 19,
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_without_memory.run(\"How many people live in canada?\")"
"agent_executor__without_memory.invoke({\"input\": \"How many people live in canada?\"})"
]
},
{
"cell_type": "code",
"execution_count": 20,
"execution_count": 29,
"id": "d9ea82f0",
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-17T15:25:53.364206Z",
"start_time": "2024-04-17T15:25:23.567528Z"
}
},
"outputs": [
{
"name": "stdout",
@ -298,29 +331,28 @@
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I should look up the answer\n",
"\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
"\u001B[32;1m\u001B[1;3m I should always think about what to do\n",
"Action: Search\n",
"Action Input: national anthem of [country]\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mMost nation states have an anthem, defined as \"a song, as of praise, devotion, or patriotism\"; most anthems are either marches or hymns in style. List of all countries around the world with its national anthem. ... Title and lyrics in the language of the country and translated into English, Aug 1, 2021 ... 1. Afghanistan, \"Milli Surood\" (National Anthem) · 2. Armenia, \"Mer Hayrenik\" (Our Fatherland) · 3. Azerbaijan (a transcontinental country with ... A national anthem is a patriotic musical composition symbolizing and evoking eulogies of the history and traditions of a country or nation. National Anthem of Every Country ; Fiji, “Meda Dau Doka” (“God Bless Fiji”) ; Finland, “Maamme”. (“Our Land”) ; France, “La Marseillaise” (“The Marseillaise”). You can find an anthem in the menu at the top alphabetically or you can use the search feature. This site is focussed on the scholarly study of national anthems ... Feb 13, 2022 ... The 38-year-old country music artist had the honor of singing the National Anthem during this year's big game, and she did not disappoint. Oldest of the World's National Anthems ; France, La Marseillaise (“The Marseillaise”), 1795 ; Argentina, Himno Nacional Argentino (“Argentine National Anthem”) ... Mar 3, 2022 ... Country music star Jessie James Decker gained the respect of music and hockey fans alike after a jaw-dropping rendition of \"The Star-Spangled ... This list shows the country on the left, the national anthem in the ... There are many countries over the world who have a national anthem of their own.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
"Final Answer: The national anthem of [country] is [name of anthem].\u001b[0m\n",
"\u001b[1m> Finished AgentExecutor chain.\u001b[0m\n"
"Action Input: \"national anthem of [country name]\"\u001B[0m\u001B[36;1m\u001B[1;3m['Most nation states have an anthem, defined as \"a song, as of praise, devotion, or patriotism\"; most anthems are either marches or hymns in style.', 'National Anthem of Every Country ; Fiji, “Meda Dau Doka” (“God Bless Fiji”) ; Finland, “Maamme”. (“Our Land”) ; France, “La Marseillaise” (“The Marseillaise”).', 'List of national anthems ; Albania · Hymni i Flamurit · Algeria ; The Bahamas · March On, Bahamaland · Bahrain ; Cambodia · Nokoreach · Cameroon ; Madagascar · Ry ...', 'General Information: First sung in 1844 with the title,. Sang till Norden (Song of the North). Its use as a. National Anthem dates from 1880-90. 1. Thou ancient ...', 'National anthem · Afghanistan · Akrotiri · Albania · Algeria · American Samoa · Andorra · Angola · Anguilla.', 'Background > National anthems: Countries Compared ; IndiaIndia, Jana Gana Mana ( Hail the ruler of all minds ) ; IndonesiaIndonesia, Indonesia Raya ( Great ...', '1. Afghanistan, \"Milli Surood\" (National Anthem) · 2. Armenia, \"Mer Hayrenik\" (Our Fatherland) · 3. Azerbaijan (a transcontinental country with ...', 'National Anthems of all the countries of the world ; Star Spangled Banner with Lyrics, Vocals, and Beautiful Photos. Musicplay ; Russia National ...', 'Himno Nacional del Perú, also known as Marcha Nacional del Perú or Somos libres, was selected as the national anthem of Peru in a public contest. Shortly after ...']\u001B[0m\u001B[32;1m\u001B[1;3mI now know the final answer\n",
"Final Answer: It depends on the country, but their national anthem can be found by searching \"national anthem of [country name]\".\u001B[0m\n",
"\n",
"\u001B[1m> Finished chain.\u001B[0m\n"
]
},
{
"data": {
"text/plain": [
"'The national anthem of [country] is [name of anthem].'"
]
"text/plain": "{'input': 'what is their national anthem called?',\n 'output': 'It depends on the country, but their national anthem can be found by searching \"national anthem of [country name]\".'}"
},
"execution_count": 20,
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_without_memory.run(\"what is their national anthem called?\")"
"agent_executor__without_memory.invoke(\n",
" {\"input\": \"what is their national anthem called?\"}\n",
")"
]
},
{

Loading…
Cancel
Save