id
stringlengths
14
16
text
stringlengths
31
3.14k
source
stringlengths
58
124
cc818135d6bf-24
_DumpException(e){throw e;}\nfunction _F_installCss(c){}\n(function(){google.jl={blt:\'none\',chnk:0,dw:false,dwu:true,emtn:0,end:0,ico:false,ikb:0,ine:false,injs:\'none\',injt:0,injth:0,injv2:false,lls:\'default\',pdt:0,rep:0,snet:true,strt:0,ubm:false,uwp:true};})();(function(){var pmc=\'{\\x22d\\x22:{},\\x22sb_he\\x22:{\\x22agen\\x22:true,\\x22cgen\\x22:true,\\x22client\\x22:\\x22heirloom-hp\\x22,\\x22dh\\x22:true,\\x22ds\\x22:\\x22\\x22,\\x22fl\\x22:true,\\x22host\\x22:\\x22google.com\\x22,\\x22jsonp\\x22:true,\\x22msgs\\x22:{\\x22cibl\\x22:\\x22Clear Search\\x22,\\x22dym\\x22:\\x22Did you mean:\\x22,\\x22lcky\\x22:\\x22I\\\\u0026#39;m Feeling Lucky\\x22,\\x22lml\\x22:\\x22Learn
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
cc818135d6bf-25
Lucky\\x22,\\x22lml\\x22:\\x22Learn more\\x22,\\x22psrc\\x22:\\x22This search was removed from your \\\\u003Ca href\\x3d\\\\\\x22/history\\\\\\x22\\\\u003EWeb History\\\\u003C/a\\\\u003E\\x22,\\x22psrl\\x22:\\x22Remove\\x22,\\x22sbit\\x22:\\x22Search by image\\x22,\\x22srch\\x22:\\x22Google Search\\x22},\\x22ovr\\x22:{},\\x22pq\\x22:\\x22\\x22,\\x22rfs\\x22:[],\\x22sbas\\x22:\\x220 3px 8px 0 rgba(0,0,0,0.2),0 0 0 1px rgba(0,0,0,0.08)\\x22,\\x22stok\\x22:\\x222J2TpqBbW29n4YEWhckcWkIgvqM\\x22}}\';google.pmc=JSON.parse(pmc);})();</script> </body></html>'
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
cc818135d6bf-26
previous Python REPL next Search Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
69e8e356f929-0
.ipynb .pdf Arxiv API Arxiv API# This notebook goes over how to use the arxiv component. First, you need to install arxiv python package. !pip install arxiv from langchain.utilities import ArxivAPIWrapper Run a query to get information about some scientific article/articles. The query text is limited to 300 characters. It returns these article fields: Publishing date Title Authors Summary Next query returns information about one article with arxiv Id equal “1605.08386”. docs = arxiv.run("1605.08386") docs 'Published: 2016-05-26\nTitle: Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias Windisch\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.' Now, we want to get information about one author, Caprice Stanley. This query returns information about three articles. By default, query returns information only about three top articles. docs = arxiv.run("Caprice Stanley") docs
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
69e8e356f929-1
'Published: 2017-10-10\nTitle: On Mixing Behavior of a Family of Random Walks Determined by a Linear Recurrence\nAuthors: Caprice Stanley, Seth Sullivant\nSummary: We study random walks on the integers mod $G_n$ that are determined by an\ninteger sequence $\\{ G_n \\}_{n \\geq 1}$ generated by a linear recurrence\nrelation. Fourier analysis provides explicit formulas to compute the\neigenvalues of the transition matrices and we use this to bound the mixing time\nof the random walks.\n\nPublished: 2016-05-26\nTitle: Heat-bath random walks with Markov bases\nAuthors: Caprice Stanley, Tobias Windisch\nSummary: Graphs on lattice points are studied whose edges come from a finite set of\nallowed moves of arbitrary length. We show that the diameter of these graphs on\nfibers of a fixed integer matrix can be bounded from above by a constant. We\nthen study the mixing behaviour of heat-bath random walks on these graphs. We\nalso state explicit conditions on the set of moves so that the heat-bath random\nwalk, a generalization of the Glauber dynamics, is an expander in fixed\ndimension.\n\nPublished: 2003-03-18\nTitle: Calculation of fluxes of charged particles and neutrinos from atmospheric showers\nAuthors: V. Plyaskin\nSummary: The results on the fluxes of
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
69e8e356f929-2
V. Plyaskin\nSummary: The results on the fluxes of charged particles and neutrinos from a\n3-dimensional (3D) simulation of atmospheric showers are presented. An\nagreement of calculated fluxes with data on charged particles from the AMS and\nCAPRICE detectors is demonstrated. Predictions on neutrino fluxes at different\nexperimental sites are compared with results from other calculations.'
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
69e8e356f929-3
Now, we are trying to find information about non-existing article. In this case, the response is “No good Arxiv Result was found” docs = arxiv.run("1605.08386WWW") docs 'No good Arxiv Result was found' previous Apify next Bash By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
9f2399fb8ff7-0
.ipynb .pdf Wikipedia API Wikipedia API# This notebook goes over how to use the wikipedia component. First, you need to install wikipedia python package. pip install wikipedia from langchain.utilities import WikipediaAPIWrapper wikipedia = WikipediaAPIWrapper() wikipedia.run('HUNTER X HUNTER')
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/wikipedia.html
9f2399fb8ff7-1
'Page: Hunter × Hunter\nSummary: Hunter × Hunter (stylized as HUNTER×HUNTER and pronounced "hunter hunter") is a Japanese manga series written and illustrated by Yoshihiro Togashi. It has been serialized in Shueisha\'s shōnen manga magazine Weekly Shōnen Jump since March 1998, although the manga has frequently gone on extended hiatuses since 2006. Its chapters have been collected in 37 tankōbon volumes as of November 2022. The story focuses on a young boy named Gon Freecss who discovers that his father, who left him at a young age, is actually a world-renowned Hunter, a licensed professional who specializes in fantastical pursuits such as locating rare or unidentified animal species, treasure hunting, surveying unexplored enclaves, or hunting down lawless individuals. Gon departs on a journey to become a Hunter and eventually find his father. Along the way, Gon meets various other Hunters and encounters the paranormal.\nHunter × Hunter was adapted into a 62-episode anime television series produced by Nippon Animation and directed by Kazuhiro Furuhashi, which ran on Fuji Television from October 1999 to March 2001. Three separate original video animations (OVAs) totaling 30 episodes were subsequently produced by Nippon Animation and released in Japan from 2002 to 2004. A second anime television series by Madhouse aired on Nippon Television from October 2011 to September 2014, totaling 148 episodes, with two animated theatrical films released in 2013. There are also numerous audio albums, video games, musicals, and other media based on Hunter × Hunter.\nThe manga has been translated into English and released in North America by Viz Media since April 2005. Both television series have been also
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/wikipedia.html
9f2399fb8ff7-2
into English and released in North America by Viz Media since April 2005. Both television series have been also licensed by Viz Media, with the first series having aired on the Funimation Channel in 2009 and the second series broadcast on Adult Swim\'s Toonami programming block from April 2016 to June 2019.\nHunter × Hunter has been a huge critical and financial success and has become one of the best-selling manga series of all time, having over 84 million copies in circulation by July 2022.\n\nPage: Hunter × Hunter (2011 TV series)\nSummary: Hunter × Hunter is an anime television series that aired from 2011 to 2014 based on Yoshihiro Togashi\'s manga series Hunter × Hunter. The story begins with a young boy named Gon Freecss, who one day discovers that the father who he thought was dead, is in fact alive and well. He learns that his father, Ging, is a legendary "Hunter", an individual who has proven themselves an elite member of humanity. Despite the fact that Ging left his son with his relatives in order to pursue his own dreams, Gon becomes determined to follow in his father\'s footsteps, pass the rigorous "Hunter Examination", and eventually find his father to become a Hunter in his own right.\nThis new Hunter × Hunter anime was announced on July 24, 2011. It is a complete reboot of the anime adaptation starting from the beginning of the manga, with no connections to the first anime from 1999. Produced by Nippon TV, VAP, Shueisha and Madhouse, the series is directed by Hiroshi Kōjina, with Atsushi Maekawa and Tsutomu Kamishiro handling series composition, Takahiro Yoshimatsu designing the characters and Yoshihisa Hirano
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/wikipedia.html
9f2399fb8ff7-3
composition, Takahiro Yoshimatsu designing the characters and Yoshihisa Hirano composing the music. Instead of having the old cast reprise their roles for the new adaptation, the series features an entirely new cast to voice the characters. The new series premiered airing weekly on Nippon TV and the nationwide Nippon News Network from October 2, 2011. The series started to be collected in both DVD and Blu-ray format on January 25, 2012. Viz Media has licensed the anime for a DVD/Blu-ray release in North America with an English dub. On television, the series began airing on Adult Swim\'s Toonami programming block on April 17, 2016, and ended on June 23, 2019.The anime series\' opening theme is alternated between the song "Departure!" and an alternate version titled "Departure! -Second Version-" both sung by Galneryus\' vocalist Masatoshi Ono. Five pieces of music were used as the ending theme; "Just Awake" by the Japanese band Fear, and Loathing in Las Vegas in episodes 1 to 26, "Hunting for Your Dream" by Galneryus in episodes 27 to 58, "Reason" sung by Japanese duo Yuzu in episodes 59 to 75, "Nagareboshi Kirari" also sung by Yuzu from episode 76 to 98, which was originally from the anime film adaptation, Hunter × Hunter: Phantom Rouge, and "Hyōri Ittai" by Yuzu featuring Hyadain from episode 99 to 146, which was also used in the film Hunter × Hunter: The Last Mission. The background music and soundtrack for the series was composed by Yoshihisa Hirano.\n\n\n\nPage: List of Hunter × Hunter characters\nSummary: The Hunter × Hunter
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/wikipedia.html
9f2399fb8ff7-4
List of Hunter × Hunter characters\nSummary: The Hunter × Hunter manga series, created by Yoshihiro Togashi, features an extensive cast of characters. It takes place in a fictional universe where licensed specialists known as Hunters travel the world taking on special jobs ranging from treasure hunting to assassination. The story initially focuses on Gon Freecss and his quest to become a Hunter in order to find his father, Ging, who is himself a famous Hunter. On the way, Gon meets and becomes close friends with Killua Zoldyck, Kurapika and Leorio Paradinight.\nAlthough most characters are human, most possess superhuman strength and/or supernatural abilities due to Nen, the ability to control one\'s own life energy or aura. The world of the series also includes fantastical beasts such as the Chimera Ants or the Five great calamities.'
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/wikipedia.html
9f2399fb8ff7-5
previous SerpAPI next Wolfram Alpha By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/wikipedia.html
2404ade73218-0
.ipynb .pdf Search Tools Contents Google Serper API Wrapper SerpAPI GoogleSearchAPIWrapper SearxNG Meta Search Engine Search Tools# This notebook shows off usage of various search tools. from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.llms import OpenAI llm = OpenAI(temperature=0) Google Serper API Wrapper# First, let’s try to use the Google Serper API tool. tools = load_tools(["google-serper"], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What is the weather in Pomfret?") > Entering new AgentExecutor chain... I should look up the current weather conditions. Action: Search Action Input: "weather in Pomfret" Observation: 37°F Thought: I now know the current temperature in Pomfret. Final Answer: The current temperature in Pomfret is 37°F. > Finished chain. 'The current temperature in Pomfret is 37°F.' SerpAPI# Now, let’s use the SerpAPI tool. tools = load_tools(["serpapi"], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What is the weather in Pomfret?") > Entering new AgentExecutor chain...
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
2404ade73218-1
> Entering new AgentExecutor chain... I need to find out what the current weather is in Pomfret. Action: Search Action Input: "weather in Pomfret" Observation: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 ... Thought: I now know the current weather in Pomfret. Final Answer: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 mph. > Finished chain. 'Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 mph.' GoogleSearchAPIWrapper# Now, let’s use the official Google Search API Wrapper. tools = load_tools(["google-search"], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What is the weather in Pomfret?") > Entering new AgentExecutor chain... I should look up the current weather conditions. Action: Google Search Action Input: "weather in Pomfret"
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
2404ade73218-2
Action: Google Search Action Input: "weather in Pomfret" Observation: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%. Pomfret, CT Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days. Hourly Weather-Pomfret, CT. As of 12:52 am EST. Special Weather Statement +2 ... Hazardous Weather Conditions. Special Weather Statement ... Pomfret CT. Tonight ... National Digital Forecast Database Maximum Temperature Forecast. Pomfret Center Weather Forecasts. Weather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for ... Pomfret, CT 12 hour by hour weather forecast includes precipitation, temperatures, sky conditions, rain chance, dew-point, relative humidity, wind direction ... North Pomfret Weather Forecasts. Weather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for ... Today's Weather - Pomfret, CT. Dec 31, 2022 4:00 PM. Putnam MS. --. Weather forecast icon. Feels like --. Hi --. Lo --. Pomfret, CT temperature trend for the next 14 Days. Find daytime highs and nighttime lows from TheWeatherNetwork.com. Pomfret, MD Weather Forecast Date: 332 PM EST Wed Dec 28 2022. The area/counties/county of: Charles, including the cites of: St. Charles and Waldorf. Thought: I now know the current weather conditions in Pomfret.
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
2404ade73218-3
Thought: I now know the current weather conditions in Pomfret. Final Answer: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%. > Finished AgentExecutor chain. 'Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%.' SearxNG Meta Search Engine# Here we will be using a self hosted SearxNG meta search engine. tools = load_tools(["searx-search"], searx_host="http://localhost:8888", llm=llm) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What is the weather in Pomfret") > Entering new AgentExecutor chain... I should look up the current weather Action: SearX Search Action Input: "weather in Pomfret" Observation: Mainly cloudy with snow showers around in the morning. High around 40F. Winds NNW at 5 to 10 mph. Chance of snow 40%. Snow accumulations less than one inch. 10 Day Weather - Pomfret, MD As of 1:37 pm EST Today 49°/ 41° 52% Mon 27 | Day 49° 52% SE 14 mph Cloudy with occasional rain showers. High 49F. Winds SE at 10 to 20 mph. Chance of rain 50%....
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
2404ade73218-4
10 Day Weather - Pomfret, VT As of 3:51 am EST Special Weather Statement Today 39°/ 32° 37% Wed 01 | Day 39° 37% NE 4 mph Cloudy with snow showers developing for the afternoon. High 39F.... Pomfret, CT ; Current Weather. 1:06 AM. 35°F · RealFeel® 32° ; TODAY'S WEATHER FORECAST. 3/3. 44°Hi. RealFeel® 50° ; TONIGHT'S WEATHER FORECAST. 3/3. 32°Lo. Pomfret, MD Forecast Today Hourly Daily Morning 41° 1% Afternoon 43° 0% Evening 35° 3% Overnight 34° 2% Don't Miss Finally, Here’s Why We Get More Colds and Flu When It’s Cold Coast-To-Coast... Pomfret, MD Weather Forecast | AccuWeather Current Weather 5:35 PM 35° F RealFeel® 36° RealFeel Shade™ 36° Air Quality Excellent Wind E 3 mph Wind Gusts 5 mph Cloudy More Details WinterCast... Pomfret, VT Weather Forecast | AccuWeather Current Weather 11:21 AM 23° F RealFeel® 27° RealFeel Shade™ 25° Air Quality Fair Wind ESE 3 mph Wind Gusts 7 mph Cloudy More Details WinterCast... Pomfret Center, CT Weather Forecast | AccuWeather Daily Current Weather 6:50 PM 39° F RealFeel® 36° Air Quality Fair Wind NW 6 mph Wind Gusts 16 mph Mostly clear More Details WinterCast... 12:00 pm · Feels Like36° · WindN 5 mph · Humidity43% · UV Index3 of 10 · Cloud Cover65% · Rain Amount0 in ...
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
2404ade73218-5
Pomfret Center, CT Weather Conditions | Weather Underground star Popular Cities San Francisco, CA 49 °F Clear Manhattan, NY 37 °F Fair Schiller Park, IL (60176) warning39 °F Mostly Cloudy... Thought: I now know the final answer Final Answer: The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%. > Finished chain. 'The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%.' previous Requests next SearxNG Search API Contents Google Serper API Wrapper SerpAPI GoogleSearchAPIWrapper SearxNG Meta Search Engine By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/tools/examples/search_tools.html
70277ed69467-0
.ipynb .pdf Custom MultiAction Agent Custom MultiAction Agent# This notebook goes through how to create your own custom agent. An agent consists of three parts: - Tools: The tools the agent has available to use. - The agent class itself: this decides which action to take. In this notebook we walk through how to create a custom agent that predicts/takes multiple steps at a time. from langchain.agents import Tool, AgentExecutor, BaseMultiActionAgent from langchain import OpenAI, SerpAPIWrapper def random_word(query: str) -> str: print("\nNow I'm doing this!") return "foo" search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name = "RandomWord", func=random_word, description="call this to get a random word." ) ] from typing import List, Tuple, Any, Union from langchain.schema import AgentAction, AgentFinish class FakeAgent(BaseMultiActionAgent): """Fake Custom Agent.""" @property def input_keys(self): return ["input"] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns:
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html
70277ed69467-1
along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ if len(intermediate_steps) == 0: return [ AgentAction(tool="Search", tool_input=kwargs["input"], log=""), AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""), ] else: return AgentFinish(return_values={"output": "bar"}, log="") async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[List[AgentAction], AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ if len(intermediate_steps) == 0: return [ AgentAction(tool="Search", tool_input=kwargs["input"], log=""), AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""), ] else: return AgentFinish(return_values={"output": "bar"}, log="") agent = FakeAgent() agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?")
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html
70277ed69467-2
> Entering new AgentExecutor chain... The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data. Now I'm doing this! foo > Finished chain. 'bar' previous Custom MRKL Agent next Custom Agent with Tool Retrieval By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html
e03e89b3f4f9-0
.ipynb .pdf Custom MRKL Agent Contents Custom LLMChain Multiple inputs Custom MRKL Agent# This notebook goes through how to create your own custom MRKL agent. A MRKL agent consists of three parts: - Tools: The tools the agent has available to use. - LLMChain: The LLMChain that produces the text that is parsed in a certain way to determine which action to take. - The agent class itself: this parses the output of the LLMChain to determine which action to take. In this notebook we walk through how to create a custom MRKL agent by creating a custom LLMChain. Custom LLMChain# The first way to create a custom agent is to use an existing Agent class, but use a custom LLMChain. This is the simplest way to create a custom Agent. It is highly recommended that you work with the ZeroShotAgent, as at the moment that is by far the most generalizable one. Most of the work in creating the custom LLMChain comes down to the prompt. Because we are using an existing agent class to parse the output, it is very important that the prompt say to produce text in that format. Additionally, we currently require an agent_scratchpad input variable to put notes on previous actions and observations. This should almost always be the final part of the prompt. However, besides those instructions, you can customize the prompt as you wish. To ensure that the prompt contains the appropriate instructions, we will utilize a helper method on that class. The helper method for the ZeroShotAgent takes the following arguments: tools: List of tools the agent will have access to, used to format the prompt. prefix: String to put before the list of tools. suffix: String to put after the list of tools.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
e03e89b3f4f9-1
suffix: String to put after the list of tools. input_variables: List of input variables the final prompt will expect. For this exercise, we will give our agent access to Google Search, and we will customize it in that we will have it answer as a pirate. from langchain.agents import ZeroShotAgent, Tool, AgentExecutor from langchain import OpenAI, SerpAPIWrapper, LLMChain search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] prefix = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:""" suffix = """Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args" Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "agent_scratchpad"] ) In case we are curious, we can now take a look at the final prompt template to see what it looks like when its all put together. print(prompt.template) Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: Search: useful for when you need to answer questions about current events Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [Search] Action Input: the input to the action
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
e03e89b3f4f9-2
Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args" Question: {input} {agent_scratchpad} Note that we are able to feed agents a self-defined prompt template, i.e. not restricted to the prompt generated by the create_prompt function, assuming it meets the agent’s requirements. For example, for ZeroShotAgent, we will need to ensure that it meets the following requirements. There should a string starting with “Action:” and a following string starting with “Action Input:”, and both should be separated by a newline. llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada Action: Search Action Input: Population of Canada 2023 Observation: The current population of Canada is 38,661,927 as of Sunday, April 16, 2023, based on Worldometer elaboration of the latest United Nations data.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
e03e89b3f4f9-3
Thought: I now know the final answer Final Answer: Arrr, Canada be havin' 38,661,927 people livin' there as of 2023! > Finished chain. "Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!" Multiple inputs# Agents can also work with prompts that require multiple inputs. prefix = """Answer the following questions as best you can. You have access to the following tools:""" suffix = """When answering, you MUST speak in the following language: {language}. Question: {input} {agent_scratchpad}""" prompt = ZeroShotAgent.create_prompt( tools, prefix=prefix, suffix=suffix, input_variables=["input", "language", "agent_scratchpad"] ) llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run(input="How many people live in canada as of 2023?", language="italian") > Entering new AgentExecutor chain... Thought: I should look for recent population estimates. Action: Search Action Input: Canada population 2023 Observation: 39,566,248 Thought: I should double check this number. Action: Search Action Input: Canada population estimates 2023
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
e03e89b3f4f9-4
Action: Search Action Input: Canada population estimates 2023 Observation: Canada's population was estimated at 39,566,248 on January 1, 2023, after a record population growth of 1,050,110 people from January 1, 2022, to January 1, 2023. Thought: I now know the final answer. Final Answer: La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023. > Finished chain. 'La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.' previous Custom LLM Agent (with a ChatModel) next Custom MultiAction Agent Contents Custom LLMChain Multiple inputs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html
fd90cd463bf0-0
.md .pdf Agent Types Contents zero-shot-react-description react-docstore self-ask-with-search conversational-react-description Agent Types# Agents use an LLM to determine which actions to take and in what order. An action can either be using a tool and observing its output, or returning a response to the user. Here are the agents available in LangChain. zero-shot-react-description# This agent uses the ReAct framework to determine which tool to use based solely on the tool’s description. Any number of tools can be provided. This agent requires that a description is provided for each tool. react-docstore# This agent uses the ReAct framework to interact with a docstore. Two tools must be provided: a Search tool and a Lookup tool (they must be named exactly as so). The Search tool should search for a document, while the Lookup tool should lookup a term in the most recently found document. This agent is equivalent to the original ReAct paper, specifically the Wikipedia example. self-ask-with-search# This agent utilizes a single tool that should be named Intermediate Answer. This tool should be able to lookup factual answers to questions. This agent is equivalent to the original self ask with search paper, where a Google search API was provided as the tool. conversational-react-description# This agent is designed to be used in conversational settings. The prompt is designed to make the agent helpful and conversational. It uses the ReAct framework to decide which tool to use, and uses memory to remember the previous conversation interactions. previous Agents next Custom Agent Contents zero-shot-react-description react-docstore self-ask-with-search
/content/https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html
fd90cd463bf0-1
react-docstore self-ask-with-search conversational-react-description By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html
4256fb2a80a0-0
.ipynb .pdf Custom Agent Custom Agent# This notebook goes through how to create your own custom agent. An agent consists of three parts: - Tools: The tools the agent has available to use. - The agent class itself: this decides which action to take. In this notebook we walk through how to create a custom agent. from langchain.agents import Tool, AgentExecutor, BaseSingleActionAgent from langchain import OpenAI, SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events", return_direct=True ) ] from typing import List, Tuple, Any, Union from langchain.schema import AgentAction, AgentFinish class FakeAgent(BaseSingleActionAgent): """Fake Custom Agent.""" @property def input_keys(self): return ["input"] def plan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any ) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ return AgentAction(tool="Search", tool_input=kwargs["input"], log="") async def aplan( self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html
4256fb2a80a0-1
) -> Union[AgentAction, AgentFinish]: """Given input, decided what to do. Args: intermediate_steps: Steps the LLM has taken to date, along with observations **kwargs: User inputs. Returns: Action specifying what tool to use. """ return AgentAction(tool="Search", tool_input=kwargs["input"], log="") agent = FakeAgent() agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data. > Finished chain. 'The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.' previous Agent Types next Custom LLM Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html
dcb1e1ca814f-0
.ipynb .pdf Custom LLM Agent Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent Adding Memory Custom LLM Agent# This notebook goes through how to create your own custom LLM agent. An LLM agent consists of three parts: PromptTemplate: This is the prompt template that can be used to instruct the language model on what to do LLM: This is the language model that powers the agent stop sequence: Instructs the LLM to stop generating as soon as this string is found OutputParser: This determines how to parse the LLMOutput into an AgentAction or AgentFinish object The LLMAgent is used in an AgentExecutor. This AgentExecutor can largely be thought of as a loop that: Passes user input and any previous steps to the Agent (in this case, the LLMAgent) If the Agent returns an AgentFinish, then return that directly to the user If the Agent returns an AgentAction, then use that to call a tool and get an Observation Repeat, passing the AgentAction and Observation back to the Agent until an AgentFinish is emitted. AgentAction is a response that consists of action and action_input. action refers to which tool to use, and action_input refers to the input to that tool. log can also be provided as more context (that can be used for logging, tracing, etc). AgentFinish is a response that contains the final message to be sent back to the user. This should be used to end an agent run. In this notebook we walk through how to create a custom LLM agent. Set up environment# Do necessary imports, etc.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-1
Set up environment# Do necessary imports, etc. from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import StringPromptTemplate from langchain import OpenAI, SerpAPIWrapper, LLMChain from typing import List, Union from langchain.schema import AgentAction, AgentFinish import re Set up tool# Set up any tools the agent may want to use. This may be necessary to put in the prompt (so that the agent knows to use these tools). # Define which tools the agent can use to answer user queries search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] Prompt Template# This instructs the agent on what to do. Generally, the template should incorporate: tools: which tools the agent has access and how and when to call them. intermediate_steps: These are tuples of previous (AgentAction, Observation) pairs. These are generally not passed directly to the model, but the prompt template formats them in a specific way. input: generic user input # Set up the base template template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-2
Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Question: {input} {agent_scratchpad}""" # Set up a prompt template class CustomPromptTemplate(StringPromptTemplate): # The template to use template: str # The list of tools available tools: List[Tool] def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools]) return self.template.format(**kwargs) prompt = CustomPromptTemplate( template=template, tools=tools,
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-3
prompt = CustomPromptTemplate( template=template, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps"] ) Output Parser# The output parser is responsible for parsing the LLM output into AgentAction and AgentFinish. This usually depends heavily on the prompt used. This is where you can change the parsing to do retries, handle whitespace, etc class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match:
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-4
if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) output_parser = CustomOutputParser() Set up LLM# Choose the LLM you want to use! llm = OpenAI(temperature=0) Define the stop sequence# This is important because it tells the LLM when to stop generation. This depends heavily on the prompt and model you are using. Generally, you want this to be whatever token you use in the prompt to denote the start of an Observation (otherwise, the LLM may hallucinate an observation for you). Set up the Agent# We can now combine everything to set up our agent # LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=llm, prompt=prompt) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) Use the Agent# Now we can use it! agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("How many people live in canada as of 2023?")
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-5
> Entering new AgentExecutor chain... Thought: I need to find out the population of Canada in 2023 Action: Search Action Input: Population of Canada in 2023 Observation:The current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data. I now know the final answer Final Answer: Arrr, there be 38,658,314 people livin' in Canada as of 2023! > Finished chain. "Arrr, there be 38,658,314 people livin' in Canada as of 2023!" Adding Memory# If you want to add memory to the agent, you’ll need to: Add a place in the custom prompt for the chat_history Add a memory object to the agent executor. # Set up the base template template_with_history = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Previous conversation history: {history} New question: {input} {agent_scratchpad}""" prompt_with_history = CustomPromptTemplate( template=template_with_history,
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-6
template=template_with_history, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps", "history"] ) llm_chain = LLMChain(llm=llm, prompt=prompt_with_history) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) from langchain.memory import ConversationBufferWindowMemory memory=ConversationBufferWindowMemory(k=2) agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, memory=memory) agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: I need to find out the population of Canada in 2023 Action: Search Action Input: Population of Canada in 2023 Observation:The current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data. I now know the final answer Final Answer: Arrr, there be 38,658,314 people livin' in Canada as of 2023! > Finished chain.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
dcb1e1ca814f-7
> Finished chain. "Arrr, there be 38,658,314 people livin' in Canada as of 2023!" agent_executor.run("how about in mexico?") > Entering new AgentExecutor chain... Thought: I need to find out how many people live in Mexico. Action: Search Action Input: How many people live in Mexico as of 2023? Observation:The current population of Mexico is 132,679,922 as of Tuesday, April 11, 2023, based on Worldometer elaboration of the latest United Nations data. Mexico 2020 ... I now know the final answer. Final Answer: Arrr, there be 132,679,922 people livin' in Mexico as of 2023! > Finished chain. "Arrr, there be 132,679,922 people livin' in Mexico as of 2023!" previous Custom Agent next Custom LLM Agent (with a ChatModel) Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent Adding Memory By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html
02ec69249e0e-0
.ipynb .pdf Custom Agent with Tool Retrieval Contents Set up environment Set up tools Tool Retriever Prompt Template Output Parser Set up LLM, stop sequence, and the agent Use the Agent Custom Agent with Tool Retrieval# This notebook builds off of this notebook and assumes familiarity with how agents work. The novel idea introduced in this notebook is the idea of using retrieval to select the set of tools to use to answer an agent query. This is useful when you have many many tools to select from. You cannot put the description of all the tools in the prompt (because of context length issues) so instead you dynamically select the N tools you do want to consider using at run time. In this notebook we will create a somewhat contrieved example. We will have one legitimate tool (search) and then 99 fake tools which are just nonsense. We will then add a step in the prompt template that takes the user input and retrieves tool relevant to the query. Set up environment# Do necessary imports, etc. from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import StringPromptTemplate from langchain import OpenAI, SerpAPIWrapper, LLMChain from typing import List, Union from langchain.schema import AgentAction, AgentFinish import re Set up tools# We will create one legitimate tool (search) and then 99 fake tools # Define which tools the agent can use to answer user queries search = SerpAPIWrapper() search_tool = Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" )
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-1
description="useful for when you need to answer questions about current events" ) def fake_func(inp: str) -> str: return "foo" fake_tools = [ Tool( name=f"foo-{i}", func=fake_func, description=f"a silly function that you can use to get more information about the number {i}" ) for i in range(99) ] ALL_TOOLS = [search_tool] + fake_tools Tool Retriever# We will use a vectorstore to create embeddings for each tool description. Then, for an incoming query we can create embeddings for that query and do a similarity search for relevant tools. from langchain.vectorstores import FAISS from langchain.embeddings import OpenAIEmbeddings from langchain.schema import Document docs = [Document(page_content=t.description, metadata={"index": i}) for i, t in enumerate(ALL_TOOLS)] vector_store = FAISS.from_documents(docs, OpenAIEmbeddings()) retriever = vector_store.as_retriever() def get_tools(query): docs = retriever.get_relevant_documents(query) return [ALL_TOOLS[d.metadata["index"]] for d in docs] We can now test this retriever to see if it seems to work. get_tools("whats the weather?")
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-2
get_tools("whats the weather?") [Tool(name='Search', description='useful for when you need to answer questions about current events', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<bound method SerpAPIWrapper.run of SerpAPIWrapper(search_engine=<class 'serpapi.google_search.GoogleSearch'>, params={'engine': 'google', 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'}, serpapi_api_key='c657176b327b17e79b55306ab968d164ee2369a7c7fa5b3f8a5f7889903de882', aiosession=None)>, coroutine=None), Tool(name='foo-95', description='a silly function that you can use to get more information about the number 95', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-3
Tool(name='foo-12', description='a silly function that you can use to get more information about the number 12', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-15', description='a silly function that you can use to get more information about the number 15', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None)] get_tools("whats the number 13?") [Tool(name='foo-13', description='a silly function that you can use to get more information about the number 13', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-4
Tool(name='foo-12', description='a silly function that you can use to get more information about the number 12', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-14', description='a silly function that you can use to get more information about the number 14', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None), Tool(name='foo-11', description='a silly function that you can use to get more information about the number 11', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None)] Prompt Template# The prompt template is pretty standard, because we’re not actually changing that much logic in the actual prompt template, but rather we are just changing how retrieval is done. # Set up the base template template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-5
{tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Question: {input} {agent_scratchpad}""" The custom prompt template now has the concept of a tools_getter, which we call on the input to select the tools to use from typing import Callable # Set up a prompt template class CustomPromptTemplate(StringPromptTemplate): # The template to use template: str ############## NEW ###################### # The list of tools available tools_getter: Callable def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts ############## NEW ###################### tools = self.tools_getter(kwargs["input"])
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-6
tools = self.tools_getter(kwargs["input"]) # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in tools]) return self.template.format(**kwargs) prompt = CustomPromptTemplate( template=template, tools_getter=get_tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps"] ) Output Parser# The output parser is unchanged from the previous notebook, since we are not changing anything about the output format. class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-7
log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)" match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) output_parser = CustomOutputParser() Set up LLM, stop sequence, and the agent# Also the same as the previous notebook llm = OpenAI(temperature=0) # LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=llm, prompt=prompt) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) Use the Agent# Now we can use it! agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True) agent_executor.run("What's the weather in SF?")
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
02ec69249e0e-8
agent_executor.run("What's the weather in SF?") > Entering new AgentExecutor chain... Thought: I need to find out what the weather is in SF Action: Search Action Input: Weather in SF Observation:Mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shifting to W at 10 to 15 mph. Humidity71%. UV Index6 of 10. I now know the final answer Final Answer: 'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10. > Finished chain. "'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10." previous Custom MultiAction Agent next Conversation Agent (for Chat Models) Contents Set up environment Set up tools Tool Retriever Prompt Template Output Parser Set up LLM, stop sequence, and the agent Use the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html
330d82ff81f6-0
.ipynb .pdf Custom LLM Agent (with a ChatModel) Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent Custom LLM Agent (with a ChatModel)# This notebook goes through how to create your own custom agent based on a chat model. An LLM chat agent consists of three parts: PromptTemplate: This is the prompt template that can be used to instruct the language model on what to do ChatModel: This is the language model that powers the agent stop sequence: Instructs the LLM to stop generating as soon as this string is found OutputParser: This determines how to parse the LLMOutput into an AgentAction or AgentFinish object The LLMAgent is used in an AgentExecutor. This AgentExecutor can largely be thought of as a loop that: Passes user input and any previous steps to the Agent (in this case, the LLMAgent) If the Agent returns an AgentFinish, then return that directly to the user If the Agent returns an AgentAction, then use that to call a tool and get an Observation Repeat, passing the AgentAction and Observation back to the Agent until an AgentFinish is emitted. AgentAction is a response that consists of action and action_input. action refers to which tool to use, and action_input refers to the input to that tool. log can also be provided as more context (that can be used for logging, tracing, etc). AgentFinish is a response that contains the final message to be sent back to the user. This should be used to end an agent run. In this notebook we walk through how to create a custom LLM agent.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
330d82ff81f6-1
In this notebook we walk through how to create a custom LLM agent. Set up environment# Do necessary imports, etc. from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser from langchain.prompts import BaseChatPromptTemplate from langchain import SerpAPIWrapper, LLMChain from langchain.chat_models import ChatOpenAI from typing import List, Union from langchain.schema import AgentAction, AgentFinish, HumanMessage import re Set up tool# Set up any tools the agent may want to use. This may be necessary to put in the prompt (so that the agent knows to use these tools). # Define which tools the agent can use to answer user queries search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ) ] Prompt Template# This instructs the agent on what to do. Generally, the template should incorporate: tools: which tools the agent has access and how and when to call them. intermediate_steps: These are tuples of previous (AgentAction, Observation) pairs. These are generally not passed directly to the model, but the prompt template formats them in a specific way. input: generic user input # Set up the base template template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}]
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
330d82ff81f6-2
Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s Question: {input} {agent_scratchpad}""" # Set up a prompt template class CustomPromptTemplate(BaseChatPromptTemplate): # The template to use template: str # The list of tools available tools: List[Tool] def format_messages(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observation tuples) # Format them in a particular way intermediate_steps = kwargs.pop("intermediate_steps") thoughts = "" for action, observation in intermediate_steps: thoughts += action.log thoughts += f"\nObservation: {observation}\nThought: " # Set the agent_scratchpad variable to that value kwargs["agent_scratchpad"] = thoughts # Create a tools variable from the list of tools provided kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools]) # Create a list of tool names for the tools provided kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools])
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
330d82ff81f6-3
formatted = self.template.format(**kwargs) return [HumanMessage(content=formatted)] prompt = CustomPromptTemplate( template=template, tools=tools, # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically # This includes the `intermediate_steps` variable because that is needed input_variables=["input", "intermediate_steps"] ) Output Parser# The output parser is responsible for parsing the LLM output into AgentAction and AgentFinish. This usually depends heavily on the prompt used. This is where you can change the parsing to do retries, handle whitespace, etc class CustomOutputParser(AgentOutputParser): def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]: # Check if agent should finish if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip()}, log=llm_output, ) # Parse out the action and action input regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
330d82ff81f6-4
match = re.search(regex, llm_output, re.DOTALL) if not match: raise ValueError(f"Could not parse LLM output: `{llm_output}`") action = match.group(1).strip() action_input = match.group(2) # Return the action and action input return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output) output_parser = CustomOutputParser() Set up LLM# Choose the LLM you want to use! llm = ChatOpenAI(temperature=0) Define the stop sequence# This is important because it tells the LLM when to stop generation. This depends heavily on the prompt and model you are using. Generally, you want this to be whatever token you use in the prompt to denote the start of an Observation (otherwise, the LLM may hallucinate an observation for you). Set up the Agent# We can now combine everything to set up our agent # LLM chain consisting of the LLM and a prompt llm_chain = LLMChain(llm=llm, prompt=prompt) tool_names = [tool.name for tool in tools] agent = LLMSingleActionAgent( llm_chain=llm_chain, output_parser=output_parser, stop=["\nObservation:"], allowed_tools=tool_names ) Use the Agent# Now we can use it! agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
330d82ff81f6-5
agent_executor.run("How many people live in canada as of 2023?") > Entering new AgentExecutor chain... Thought: Wot year be it now? That be important to know the answer. Action: Search Action Input: "current population canada 2023" Observation:38,649,283Ahoy! That be the correct year, but the answer be in regular numbers. 'Tis time to translate to pirate speak. Action: Search Action Input: "38,649,283 in pirate speak" Observation:Brush up on your “Pirate Talk” with these helpful pirate phrases. Aaaarrrrgggghhhh! Pirate catch phrase of grumbling or disgust. Ahoy! Hello! Ahoy, Matey, Hello ...That be not helpful, I'll just do the translation meself. Final Answer: Arrrr, thar be 38,649,283 scallywags in Canada as of 2023. > Finished chain. 'Arrrr, thar be 38,649,283 scallywags in Canada as of 2023.' previous Custom LLM Agent next Custom MRKL Agent Contents Set up environment Set up tool Prompt Template Output Parser Set up LLM Define the stop sequence Set up the Agent Use the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html
d93bb485eca7-0
.ipynb .pdf Conversation Agent Conversation Agent# This notebook walks through using an agent optimized for conversation. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well. This is accomplished with a specific type of agent (conversational-react-description) which expects to be used with a memory component. from langchain.agents import Tool from langchain.agents import AgentType from langchain.memory import ConversationBufferMemory from langchain import OpenAI from langchain.utilities import SerpAPIWrapper from langchain.agents import initialize_agent search = SerpAPIWrapper() tools = [ Tool( name = "Current Search", func=search.run, description="useful for when you need to answer questions about current events or the current state of the world" ), ] memory = ConversationBufferMemory(memory_key="chat_history") llm=OpenAI(temperature=0) agent_chain = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory) agent_chain.run(input="hi, i am bob") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? No AI: Hi Bob, nice to meet you! How can I help you today? > Finished chain. 'Hi Bob, nice to meet you! How can I help you today?' agent_chain.run(input="what's my name?") > Entering new AgentExecutor chain...
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html
d93bb485eca7-1
> Entering new AgentExecutor chain... Thought: Do I need to use a tool? No AI: Your name is Bob! > Finished chain. 'Your name is Bob!' agent_chain.run("what are some good dinners to make this week, if i like thai food?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Current Search Action Input: Thai food dinner recipes Observation: 59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's Thai Spicy ... Thought: Do I need to use a tool? No AI: Here are some great Thai dinner recipes you can try this week: Marion Grasby's Thai Spicy Chilli and Basil Fried Rice, Thai Curry Noodle Soup, Thai Green Curry with Coconut Rice, Thai Red Curry with Vegetables, and Thai Coconut Soup. I hope you enjoy them! > Finished chain. "Here are some great Thai dinner recipes you can try this week: Marion Grasby's Thai Spicy Chilli and Basil Fried Rice, Thai Curry Noodle Soup, Thai Green Curry with Coconut Rice, Thai Red Curry with Vegetables, and Thai Coconut Soup. I hope you enjoy them!" agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Current Search Action Input: Who won the World Cup in 1978 Observation: Argentina national football team Thought: Do I need to use a tool? No
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html
d93bb485eca7-2
Observation: Argentina national football team Thought: Do I need to use a tool? No AI: The last letter in your name is "b" and the winner of the 1978 World Cup was the Argentina national football team. > Finished chain. 'The last letter in your name is "b" and the winner of the 1978 World Cup was the Argentina national football team.' agent_chain.run(input="whats the current temperature in pomfret?") > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Current Search Action Input: Current temperature in Pomfret Observation: Partly cloudy skies. High around 70F. Winds W at 5 to 10 mph. Humidity41%. Thought: Do I need to use a tool? No AI: The current temperature in Pomfret is around 70F with partly cloudy skies and winds W at 5 to 10 mph. The humidity is 41%. > Finished chain. 'The current temperature in Pomfret is around 70F with partly cloudy skies and winds W at 5 to 10 mph. The humidity is 41%.' previous Conversation Agent (for Chat Models) next MRKL By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html
619cc53cdb76-0
.ipynb .pdf MRKL Chat MRKL Chat# This notebook showcases using an agent to replicate the MRKL chain using an agent optimized for chat models. This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. from langchain import OpenAI, LLMMathChain, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.chat_models import ChatOpenAI llm = ChatOpenAI(temperature=0) llm1 = OpenAI(temperature=0) search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm1, verbose=True) db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db") db_chain = SQLDatabaseChain(llm=llm1, database=db, verbose=True) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions" ), Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math" ), Tool( name="FooBar DB", func=db_chain.run,
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
619cc53cdb76-1
), Tool( name="FooBar DB", func=db_chain.run, description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context" ) ] mrkl = initialize_agent(tools, llm, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True) mrkl.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... Thought: The first question requires a search, while the second question requires a calculator. Action: ``` { "action": "Search", "action_input": "Leo DiCaprio girlfriend" } ``` Observation: Gigi Hadid: 2022 Leo and Gigi were first linked back in September 2022, when a source told Us Weekly that Leo had his “sights set" on her (alarming way to put it, but okay). Thought:For the second question, I need to calculate the age raised to the 0.43 power. I will use the calculator tool. Action: ``` { "action": "Calculator", "action_input": "((2022-1995)^0.43)" } ``` > Entering new LLMMathChain chain... ((2022-1995)^0.43) ```text (2022-1995)**0.43 ``` ...numexpr.evaluate("(2022-1995)**0.43")... Answer: 4.125593352125936 > Finished chain. Observation: Answer: 4.125593352125936 Thought:I now know the final answer.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
619cc53cdb76-2
Thought:I now know the final answer. Final Answer: Gigi Hadid is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is approximately 4.13. > Finished chain. "Gigi Hadid is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is approximately 4.13." mrkl.run("What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database?") > Entering new AgentExecutor chain... Question: What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database? Thought: I should use the Search tool to find the answer to the first part of the question and then use the FooBar DB tool to find the answer to the second part. Action: ``` { "action": "Search", "action_input": "Who recently released an album called 'The Storm Before the Calm'" } ``` Observation: Alanis Morissette Thought:Now that I know the artist's name, I can use the FooBar DB tool to find out if they are in the database and what albums of theirs are in it. Action: ``` { "action": "FooBar DB", "action_input": "What albums does Alanis Morissette have in the database?" } ``` > Entering new SQLDatabaseChain chain... What albums does Alanis Morissette have in the database? SQLQuery:
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
619cc53cdb76-3
What albums does Alanis Morissette have in the database? SQLQuery: /Users/harrisonchase/workplace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage. sample_rows = connection.execute(command) SELECT "Title" FROM "Album" WHERE "ArtistId" IN (SELECT "ArtistId" FROM "Artist" WHERE "Name" = 'Alanis Morissette') LIMIT 5; SQLResult: [('Jagged Little Pill',)] Answer: Alanis Morissette has the album Jagged Little Pill in the database. > Finished chain. Observation: Alanis Morissette has the album Jagged Little Pill in the database. Thought:The artist Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it. Final Answer: Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it. > Finished chain. 'Alanis Morissette is in the FooBar database and has the album Jagged Little Pill in it.' previous MRKL next ReAct By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html
bea49bafd3e5-0
.ipynb .pdf Conversation Agent (for Chat Models) Conversation Agent (for Chat Models)# This notebook walks through using an agent optimized for conversation, using ChatModels. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well. This is accomplished with a specific type of agent (chat-conversational-react-description) which expects to be used with a memory component. import os os.environ["LANGCHAIN_HANDLER"] = "langchain" from langchain.agents import Tool from langchain.memory import ConversationBufferMemory from langchain.chat_models import ChatOpenAI from langchain.utilities import SerpAPIWrapper from langchain.agents import initialize_agent from langchain.agents import AgentType WARNING:root:Failed to default session, using empty session: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /sessions (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10a1767c0>: Failed to establish a new connection: [Errno 61] Connection refused')) search = SerpAPIWrapper() tools = [ Tool( name = "Current Search", func=search.run, description="useful for when you need to answer questions about current events or the current state of the world. the input to this should be a single search term." ), ]
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
bea49bafd3e5-1
), ] memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) llm=ChatOpenAI(temperature=0) agent_chain = initialize_agent(tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory) agent_chain.run(input="hi, i am bob") > Entering new AgentExecutor chain... WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fab40d0>: Failed to establish a new connection: [Errno 61] Connection refused')) { "action": "Final Answer", "action_input": "Hello Bob! How can I assist you today?" } > Finished chain. 'Hello Bob! How can I assist you today?' agent_chain.run(input="what's my name?") > Entering new AgentExecutor chain... WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fab44f0>: Failed to establish a new connection: [Errno 61] Connection refused')) { "action": "Final Answer",
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
bea49bafd3e5-2
{ "action": "Final Answer", "action_input": "Your name is Bob." } > Finished chain. 'Your name is Bob.' agent_chain.run("what are some good dinners to make this week, if i like thai food?") > Entering new AgentExecutor chain... { "action": "Current Search", "action_input": "Thai food dinner recipes" } Observation: 59 easy Thai recipes for any night of the week · Marion Grasby's Thai spicy chilli and basil fried rice · Thai curry noodle soup · Marion Grasby's Thai Spicy ... Thought: WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fae8be0>: Failed to establish a new connection: [Errno 61] Connection refused')) { "action": "Final Answer", "action_input": "Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and Thai Spicy ... (59 recipes in total)." } > Finished chain. 'Here are some Thai food dinner recipes you can make this week: Thai spicy chilli and basil fried rice, Thai curry noodle soup, and Thai Spicy ... (59 recipes in total).'
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
bea49bafd3e5-3
agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?") > Entering new AgentExecutor chain... ```json { "action": "Current Search", "action_input": "who won the world cup in 1978" } ``` Observation: Argentina national football team Thought: WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fae86d0>: Failed to establish a new connection: [Errno 61] Connection refused')) ```json { "action": "Final Answer", "action_input": "The last letter in your name is 'b', and the winner of the 1978 World Cup was the Argentina national football team." } ``` > Finished chain. "The last letter in your name is 'b', and the winner of the 1978 World Cup was the Argentina national football team." agent_chain.run(input="whats the weather like in pomfret?") > Entering new AgentExecutor chain... { "action": "Current Search", "action_input": "weather in pomfret" } Observation: 10 Day Weather-Pomfret, CT ; Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph. Thought:
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
bea49bafd3e5-4
Thought: WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fa9d7f0>: Failed to establish a new connection: [Errno 61] Connection refused')) { "action": "Final Answer", "action_input": "The weather in Pomfret, CT for the next 10 days is as follows: Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph." } > Finished chain. 'The weather in Pomfret, CT for the next 10 days is as follows: Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph.' previous Custom Agent with Tool Retrieval next Conversation Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html
8f5fee1969aa-0
.ipynb .pdf ReAct ReAct# This notebook showcases using an agent to implement the ReAct logic. from langchain import OpenAI, Wikipedia from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.agents.react.base import DocstoreExplorer docstore=DocstoreExplorer(Wikipedia()) tools = [ Tool( name="Search", func=docstore.search, description="useful for when you need to ask with search" ), Tool( name="Lookup", func=docstore.lookup, description="useful for when you need to ask with lookup" ) ] llm = OpenAI(temperature=0, model_name="text-davinci-002") react = initialize_agent(tools, llm, agent=AgentType.REACT_DOCSTORE, verbose=True) question = "Author David Chanoff has collaborated with a U.S. Navy admiral who served as the ambassador to the United Kingdom under which President?" react.run(question) > Entering new AgentExecutor chain... Thought: I need to search David Chanoff and find the U.S. Navy admiral he collaborated with. Then I need to find which President the admiral served under. Action: Search[David Chanoff]
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/react.html
8f5fee1969aa-1
Action: Search[David Chanoff] Observation: David Chanoff is a noted author of non-fiction work. His work has typically involved collaborations with the principal protagonist of the work concerned. His collaborators have included; Augustus A. White, Joycelyn Elders, Đoàn Văn Toại, William J. Crowe, Ariel Sharon, Kenneth Good and Felix Zandman. He has also written about a wide range of subjects including literary history, education and foreign for The Washington Post, The New Republic and The New York Times Magazine. He has published more than twelve books. Thought: The U.S. Navy admiral David Chanoff collaborated with is William J. Crowe. I need to find which President he served under. Action: Search[William J. Crowe] Observation: William James Crowe Jr. (January 2, 1925 – October 18, 2007) was a United States Navy admiral and diplomat who served as the 11th chairman of the Joint Chiefs of Staff under Presidents Ronald Reagan and George H. W. Bush, and as the ambassador to the United Kingdom and Chair of the Intelligence Oversight Board under President Bill Clinton. Thought: William J. Crowe served as the ambassador to the United Kingdom under President Bill Clinton, so the answer is Bill Clinton. Action: Finish[Bill Clinton] > Finished chain. 'Bill Clinton' previous MRKL Chat next Self Ask With Search By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/react.html
20edeaeb035a-0
.ipynb .pdf Self Ask With Search Self Ask With Search# This notebook showcases the Self Ask With Search chain. from langchain import OpenAI, SerpAPIWrapper from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType llm = OpenAI(temperature=0) search = SerpAPIWrapper() tools = [ Tool( name="Intermediate Answer", func=search.run, description="useful for when you need to ask with search" ) ] self_ask_with_search = initialize_agent(tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True) self_ask_with_search.run("What is the hometown of the reigning men's U.S. Open champion?") > Entering new AgentExecutor chain... Yes. Follow up: Who is the reigning men's U.S. Open champion? Intermediate answer: Carlos Alcaraz Garfia Follow up: Where is Carlos Alcaraz Garfia from? Intermediate answer: El Palmar, Spain So the final answer is: El Palmar, Spain > Finished chain. 'El Palmar, Spain' previous ReAct next Toolkits By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/self_ask_with_search.html
3b774017deb4-0
.ipynb .pdf MRKL MRKL# This notebook showcases using an agent to replicate the MRKL chain. This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. from langchain import LLMMathChain, OpenAI, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType llm = OpenAI(temperature=0) search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm, verbose=True) db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db") db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True) tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions" ), Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math" ), Tool( name="FooBar DB", func=db_chain.run, description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context" ) ]
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
3b774017deb4-1
) ] mrkl = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) mrkl.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power. Action: Search Action Input: "Who is Leo DiCaprio's girlfriend?" Observation: DiCaprio met actor Camila Morrone in December 2017, when she was 20 and he was 43. They were spotted at Coachella and went on multiple vacations together. Some reports suggested that DiCaprio was ready to ask Morrone to marry him. The couple made their red carpet debut at the 2020 Academy Awards. Thought: I need to calculate Camila Morrone's age raised to the 0.43 power. Action: Calculator Action Input: 21^0.43 > Entering new LLMMathChain chain... 21^0.43 ```text 21**0.43 ``` ...numexpr.evaluate("21**0.43")... Answer: 3.7030049853137306 > Finished chain. Observation: Answer: 3.7030049853137306 Thought: I now know the final answer. Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.7030049853137306. > Finished chain. "Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.7030049853137306."
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
3b774017deb4-2
mrkl.run("What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database?") > Entering new AgentExecutor chain... I need to find out the artist's full name and then search the FooBar database for their albums. Action: Search Action Input: "The Storm Before the Calm" artist Observation: The Storm Before the Calm (stylized in all lowercase) is the tenth (and eighth international) studio album by Canadian-American singer-songwriter Alanis Morissette, released June 17, 2022, via Epiphany Music and Thirty Tigers, as well as by RCA Records in Europe. Thought: I now need to search the FooBar database for Alanis Morissette's albums. Action: FooBar DB Action Input: What albums by Alanis Morissette are in the FooBar database? > Entering new SQLDatabaseChain chain... What albums by Alanis Morissette are in the FooBar database? SQLQuery: /Users/harrisonchase/workplace/langchain/langchain/sql_database.py:191: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage. sample_rows = connection.execute(command)
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
3b774017deb4-3
sample_rows = connection.execute(command) SELECT "Title" FROM "Album" INNER JOIN "Artist" ON "Album"."ArtistId" = "Artist"."ArtistId" WHERE "Name" = 'Alanis Morissette' LIMIT 5; SQLResult: [('Jagged Little Pill',)] Answer: The albums by Alanis Morissette in the FooBar database are Jagged Little Pill. > Finished chain. Observation: The albums by Alanis Morissette in the FooBar database are Jagged Little Pill. Thought: I now know the final answer. Final Answer: The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill. > Finished chain. "The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill." previous Conversation Agent next MRKL Chat By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html
03c6e2e9dce9-0
.ipynb .pdf SQL Database Agent Contents Initialization Example: describing a table Example: describing a table, recovering from an error Example: running queries Recovering from an error SQL Database Agent# This notebook showcases an agent designed to interact with a sql databases. The agent builds off of SQLDatabaseChain and is designed to answer more general questions about a database, as well as recover from errors. Note that, as this agent is in active development, all answers might not be correct. Additionally, it is not guaranteed that the agent won’t perform DML statements on your database given certain questions. Be careful running it on sensitive data! This uses the example Chinook database. To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository. Initialization# from langchain.agents import create_sql_agent from langchain.agents.agent_toolkits import SQLDatabaseToolkit from langchain.sql_database import SQLDatabase from langchain.llms.openai import OpenAI from langchain.agents import AgentExecutor db = SQLDatabase.from_uri("sqlite:///../../../../notebooks/Chinook.db") toolkit = SQLDatabaseToolkit(db=db) agent_executor = create_sql_agent( llm=OpenAI(temperature=0), toolkit=toolkit, verbose=True ) Example: describing a table# agent_executor.run("Describe the playlisttrack table")
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-1
agent_executor.run("Describe the playlisttrack table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Artist, Invoice, Playlist, Genre, Album, PlaylistTrack, Track, InvoiceLine, MediaType, Employee, Customer Thought: I should look at the schema of the playlisttrack table Action: schema_sql_db Action Input: "PlaylistTrack" Observation: CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I now know the final answer Final Answer: The PlaylistTrack table has two columns, PlaylistId and TrackId, and is linked to the Playlist and Track tables. > Finished chain. 'The PlaylistTrack table has two columns, PlaylistId and TrackId, and is linked to the Playlist and Track tables.' Example: describing a table, recovering from an error# In this example, the agent tries to search for a table that doesn’t exist, but finds the next best result agent_executor.run("Describe the playlistsong table")
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-2
agent_executor.run("Describe the playlistsong table") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: I should look at the schema of the PlaylistSong table Action: schema_sql_db Action Input: "PlaylistSong" Observation: Error: table_names {'PlaylistSong'} not found in database Thought: I should check the spelling of the table Action: list_tables_sql_db Action Input: "" Observation: Genre, PlaylistTrack, MediaType, Invoice, InvoiceLine, Track, Playlist, Customer, Album, Employee, Artist Thought: The table is called PlaylistTrack Action: schema_sql_db Action Input: "PlaylistTrack" Observation: CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I now know the final answer
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-3
1 3402 1 3389 1 3390 Thought: I now know the final answer Final Answer: The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables. > Finished chain. 'The PlaylistTrack table contains two columns, PlaylistId and TrackId, which are both integers and are used to link Playlist and Track tables.' Example: running queries# agent_executor.run("List the total sales per country. Which country's customers spent the most?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the relevant tables to see what columns I can use. Action: schema_sql_db Action Input: "Invoice, Customer" Observation: CREATE TABLE "Customer" ( "CustomerId" INTEGER NOT NULL, "FirstName" NVARCHAR(40) NOT NULL, "LastName" NVARCHAR(20) NOT NULL, "Company" NVARCHAR(80), "Address" NVARCHAR(70), "City" NVARCHAR(40), "State" NVARCHAR(40), "Country" NVARCHAR(40), "PostalCode" NVARCHAR(10), "Phone" NVARCHAR(24), "Fax" NVARCHAR(24), "Email" NVARCHAR(60) NOT NULL,
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-4
"Email" NVARCHAR(60) NOT NULL, "SupportRepId" INTEGER, PRIMARY KEY ("CustomerId"), FOREIGN KEY("SupportRepId") REFERENCES "Employee" ("EmployeeId") ) SELECT * FROM 'Customer' LIMIT 3; CustomerId FirstName LastName Company Address City State Country PostalCode Phone Fax Email SupportRepId 1 Luís Gonçalves Embraer - Empresa Brasileira de Aeronáutica S.A. Av. Brigadeiro Faria Lima, 2170 São José dos Campos SP Brazil 12227-000 +55 (12) 3923-5555 +55 (12) 3923-5566 [email protected] 3 2 Leonie Köhler None Theodor-Heuss-Straße 34 Stuttgart None Germany 70174 +49 0711 2842222 None [email protected] 5 3 François Tremblay None 1498 rue Bélanger Montréal QC Canada H2G 1A7 +1 (514) 721-4711 None [email protected] 3 CREATE TABLE "Invoice" ( "InvoiceId" INTEGER NOT NULL, "CustomerId" INTEGER NOT NULL, "InvoiceDate" DATETIME NOT NULL, "BillingAddress" NVARCHAR(70), "BillingCity" NVARCHAR(40), "BillingState" NVARCHAR(40), "BillingCountry" NVARCHAR(40), "BillingPostalCode" NVARCHAR(10), "Total" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("InvoiceId"),
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-5
PRIMARY KEY ("InvoiceId"), FOREIGN KEY("CustomerId") REFERENCES "Customer" ("CustomerId") ) SELECT * FROM 'Invoice' LIMIT 3; InvoiceId CustomerId InvoiceDate BillingAddress BillingCity BillingState BillingCountry BillingPostalCode Total 1 2 2009-01-01 00:00:00 Theodor-Heuss-Straße 34 Stuttgart None Germany 70174 1.98 2 4 2009-01-02 00:00:00 Ullevålsveien 14 Oslo None Norway 0171 3.96 3 8 2009-01-03 00:00:00 Grétrystraat 63 Brussels None Belgium 1000 5.94 Thought: I should query the Invoice and Customer tables to get the total sales per country. Action: query_sql_db Action Input: SELECT c.Country, SUM(i.Total) AS TotalSales FROM Invoice i INNER JOIN Customer c ON i.CustomerId = c.CustomerId GROUP BY c.Country ORDER BY TotalSales DESC LIMIT 10 Observation: [('USA', 523.0600000000003), ('Canada', 303.9599999999999), ('France', 195.09999999999994), ('Brazil', 190.09999999999997), ('Germany', 156.48), ('United Kingdom', 112.85999999999999), ('Czech Republic', 90.24000000000001), ('Portugal', 77.23999999999998), ('India', 75.25999999999999), ('Chile', 46.62)] Thought: I now know the final answer
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-6
Thought: I now know the final answer Final Answer: The customers from the USA spent the most, with a total of $523.06. > Finished chain. 'The customers from the USA spent the most, with a total of $523.06.' agent_executor.run("Show the total number of tracks in each playlist. The Playlist name should be included in the result.") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: Invoice, MediaType, Artist, InvoiceLine, Genre, Playlist, Employee, Album, PlaylistTrack, Track, Customer Thought: I should look at the schema of the Playlist and PlaylistTrack tables to see what columns I can use. Action: schema_sql_db Action Input: "Playlist, PlaylistTrack" Observation: CREATE TABLE "Playlist" ( "PlaylistId" INTEGER NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("PlaylistId") ) SELECT * FROM 'Playlist' LIMIT 3; PlaylistId Name 1 Music 2 Movies 3 TV Shows CREATE TABLE "PlaylistTrack" ( "PlaylistId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, PRIMARY KEY ("PlaylistId", "TrackId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId") ) SELECT * FROM 'PlaylistTrack' LIMIT 3; PlaylistId TrackId
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-7
PlaylistId TrackId 1 3402 1 3389 1 3390 Thought: I can use a SELECT statement to get the total number of tracks in each playlist. Action: query_checker_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Observation: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name Thought: The query looks correct, I can now execute it. Action: query_sql_db Action Input: SELECT Playlist.Name, COUNT(PlaylistTrack.TrackId) AS TotalTracks FROM Playlist INNER JOIN PlaylistTrack ON Playlist.PlaylistId = PlaylistTrack.PlaylistId GROUP BY Playlist.Name LIMIT 10 Observation: [('90’s Music', 1477), ('Brazilian Music', 39), ('Classical', 75), ('Classical 101 - Deep Cuts', 25), ('Classical 101 - Next Steps', 25), ('Classical 101 - The Basics', 25), ('Grunge', 15), ('Heavy Metal Classic', 26), ('Music', 6580), ('Music Videos', 1)] Thought: I now know the final answer.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-8
Thought: I now know the final answer. Final Answer: The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1). > Finished chain. "The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (6580), 'Music Videos' (1)." Recovering from an error# In this example, the agent is able to recover from an error after initially trying to access an attribute (Track.ArtistId) which doesn’t exist. agent_executor.run("Who are the top 3 best selling artists?") > Entering new AgentExecutor chain... Action: list_tables_sql_db Action Input: "" Observation: MediaType, Track, Invoice, Album, Playlist, Customer, Employee, InvoiceLine, PlaylistTrack, Genre, Artist Thought: I should look at the schema of the Artist, InvoiceLine, and Track tables to see what columns I can use. Action: schema_sql_db Action Input: "Artist, InvoiceLine, Track"
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-9
Action Input: "Artist, InvoiceLine, Track" Observation: CREATE TABLE "Artist" ( "ArtistId" INTEGER NOT NULL, "Name" NVARCHAR(120), PRIMARY KEY ("ArtistId") ) SELECT * FROM 'Artist' LIMIT 3; ArtistId Name 1 AC/DC 2 Accept 3 Aerosmith CREATE TABLE "Track" ( "TrackId" INTEGER NOT NULL, "Name" NVARCHAR(200) NOT NULL, "AlbumId" INTEGER, "MediaTypeId" INTEGER NOT NULL, "GenreId" INTEGER, "Composer" NVARCHAR(220), "Milliseconds" INTEGER NOT NULL, "Bytes" INTEGER, "UnitPrice" NUMERIC(10, 2) NOT NULL, PRIMARY KEY ("TrackId"), FOREIGN KEY("MediaTypeId") REFERENCES "MediaType" ("MediaTypeId"), FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"), FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId") ) SELECT * FROM 'Track' LIMIT 3; TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice 1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 11170334 0.99 2 Balls to the Wall 2 2 1 None 342562 5510424 0.99
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-10
2 Balls to the Wall 2 2 1 None 342562 5510424 0.99 3 Fast As a Shark 3 2 1 F. Baltes, S. Kaufman, U. Dirkscneider & W. Hoffman 230619 3990994 0.99 CREATE TABLE "InvoiceLine" ( "InvoiceLineId" INTEGER NOT NULL, "InvoiceId" INTEGER NOT NULL, "TrackId" INTEGER NOT NULL, "UnitPrice" NUMERIC(10, 2) NOT NULL, "Quantity" INTEGER NOT NULL, PRIMARY KEY ("InvoiceLineId"), FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"), FOREIGN KEY("InvoiceId") REFERENCES "Invoice" ("InvoiceId") ) SELECT * FROM 'InvoiceLine' LIMIT 3; InvoiceLineId InvoiceId TrackId UnitPrice Quantity 1 1 2 0.99 1 2 1 4 0.99 1 3 2 6 0.99 1 Thought: I should query the database to get the top 3 best selling artists. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-11
Observation: Error: (sqlite3.OperationalError) no such column: Track.ArtistId [SQL: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3] (Background on this error at: https://sqlalche.me/e/14/e3q8) Thought: I should double check my query before executing it. Action: query_checker_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3; Thought: I now know the final answer. Action: query_sql_db
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
03c6e2e9dce9-12
Thought: I now know the final answer. Action: query_sql_db Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Album ON Artist.ArtistId = Album.ArtistId INNER JOIN Track ON Album.AlbumId = Track.AlbumId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER BY TotalQuantity DESC LIMIT 3 Observation: [('Iron Maiden', 140), ('U2', 107), ('Metallica', 91)] Thought: I now know the final answer. Final Answer: The top 3 best selling artists are Iron Maiden, U2, and Metallica. > Finished chain. 'The top 3 best selling artists are Iron Maiden, U2, and Metallica.' previous Python Agent next Vectorstore Agent Contents Initialization Example: describing a table Example: describing a table, recovering from an error Example: running queries Recovering from an error By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html
ef29d9ea4bc2-0
.ipynb .pdf CSV Agent CSV Agent# This notebook shows how to use agents to interact with a csv. It is mostly optimized for question answering. NOTE: this agent calls the Pandas DataFrame agent under the hood, which in turn calls the Python agent, which executes LLM generated Python code - this can be bad if the LLM generated Python code is harmful. Use cautiously. from langchain.agents import create_csv_agent from langchain.llms import OpenAI agent = create_csv_agent(OpenAI(temperature=0), 'titanic.csv', verbose=True) agent.run("how many rows are there?") > Entering new AgentExecutor chain... Thought: I need to count the number of rows Action: python_repl_ast Action Input: len(df) Observation: 891 Thought: I now know the final answer Final Answer: There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.' agent.run("how many people have more than 3 sibligngs") > Entering new AgentExecutor chain... Thought: I need to count the number of people with more than 3 siblings Action: python_repl_ast Action Input: df[df['SibSp'] > 3].shape[0] Observation: 30 Thought: I now know the final answer Final Answer: 30 people have more than 3 siblings. > Finished chain. '30 people have more than 3 siblings.' agent.run("whats the square root of the average age?")
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/csv.html
ef29d9ea4bc2-1
agent.run("whats the square root of the average age?") > Entering new AgentExecutor chain... Thought: I need to calculate the average age first Action: python_repl_ast Action Input: df['Age'].mean() Observation: 29.69911764705882 Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: name 'math' is not defined Thought: I need to import the math library Action: python_repl_ast Action Input: import math Observation: Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: 5.449689683556195 Thought: I now know the final answer Final Answer: 5.449689683556195 > Finished chain. '5.449689683556195' previous Toolkits next Jira By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/csv.html
ed7a79af929d-0
.ipynb .pdf Natural Language APIs Contents First, import dependencies and load the LLM Next, load the Natural Language API Toolkits Create the Agent Using Auth + Adding more Endpoints Thank you! Natural Language APIs# Natural Language API Toolkits (NLAToolkits) permit LangChain Agents to efficiently plan and combine calls across endpoints. This notebook demonstrates a sample composition of the Speak, Klarna, and Spoonacluar APIs. For a detailed walkthrough of the OpenAPI chains wrapped within the NLAToolkit, see the OpenAPI Operation Chain notebook. First, import dependencies and load the LLM# from typing import List, Optional from langchain.chains import LLMChain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.requests import Requests from langchain.tools import APIOperation, OpenAPISpec from langchain.agents import AgentType, Tool, initialize_agent from langchain.agents.agent_toolkits import NLAToolkit # Select the LLM to use. Here, we use text-davinci-003 llm = OpenAI(temperature=0, max_tokens=700) # You can swap between different core LLM's here. Next, load the Natural Language API Toolkits# speak_toolkit = NLAToolkit.from_llm_and_url(llm, "https://api.speak.com/openapi.yaml") klarna_toolkit = NLAToolkit.from_llm_and_url(llm, "https://www.klarna.com/us/shopping/public/openai/v0/api-docs/")
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-1
Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Create the Agent# # Slightly tweak the instructions from the default agent openapi_format_instructions = """Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: what to instruct the AI Action representative. Observation: The Agent's response ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer. User can't see any of my observations, API responses, links, or tools. Final Answer: the final answer to the original input question with the right amount of detail When responding with your Final Answer, remember that the person you are responding to CANNOT see any of your Thought/Action/Action Input/Observations, so if there is any relevant information there you need to include it explicitly in your response.""" natural_language_tools = speak_toolkit.get_tools() + klarna_toolkit.get_tools() mrkl = initialize_agent(natural_language_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-2
verbose=True, agent_kwargs={"format_instructions":openapi_format_instructions}) mrkl.run("I have an end of year party for my Italian class and have to buy some Italian clothes for it") > Entering new AgentExecutor chain... I need to find out what kind of Italian clothes are available Action: Open_AI_Klarna_product_Api.productsUsingGET Action Input: Italian clothes Observation: The API response contains two products from the Alé brand in Italian Blue. The first is the Alé Colour Block Short Sleeve Jersey Men - Italian Blue, which costs $86.49, and the second is the Alé Dolid Flash Jersey Men - Italian Blue, which costs $40.00. Thought: I now know what kind of Italian clothes are available and how much they cost. Final Answer: You can buy two products from the Alé brand in Italian Blue for your end of year party. The Alé Colour Block Short Sleeve Jersey Men - Italian Blue costs $86.49, and the Alé Dolid Flash Jersey Men - Italian Blue costs $40.00. > Finished chain. 'You can buy two products from the Alé brand in Italian Blue for your end of year party. The Alé Colour Block Short Sleeve Jersey Men - Italian Blue costs $86.49, and the Alé Dolid Flash Jersey Men - Italian Blue costs $40.00.' Using Auth + Adding more Endpoints# Some endpoints may require user authentication via things like access tokens. Here we show how to pass in the authentication information via the Requests wrapper object.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-3
Since each NLATool exposes a concisee natural language interface to its wrapped API, the top level conversational agent has an easier job incorporating each endpoint to satisfy a user’s request. Adding the Spoonacular endpoints. Go to the Spoonacular API Console and make a free account. Click on Profile and copy your API key below. spoonacular_api_key = "" # Copy from the API Console requests = Requests(headers={"x-api-key": spoonacular_api_key}) spoonacular_toolkit = NLAToolkit.from_llm_and_url( llm, "https://spoonacular.com/application/frontend/downloads/spoonacular-openapi-3.json", requests=requests, max_text_length=1800, # If you want to truncate the response text ) Attempting to load an OpenAPI 3.0.0 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support. Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-4
Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-5
Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter natural_language_api_tools = (speak_toolkit.get_tools() + klarna_toolkit.get_tools() + spoonacular_toolkit.get_tools()[:30] ) print(f"{len(natural_language_api_tools)} tools loaded.") 34 tools loaded. # Create an agent with the new tools mrkl = initialize_agent(natural_language_api_tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, agent_kwargs={"format_instructions":openapi_format_instructions}) # Make the query more complex! user_input = ( "I'm learning Italian, and my language class is having an end of year party... " " Could you help me find an Italian outfit to wear and" " an appropriate recipe to prepare so I can present for the class in Italian?" ) mrkl.run(user_input) > Entering new AgentExecutor chain...
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-6
) mrkl.run(user_input) > Entering new AgentExecutor chain... I need to find a recipe and an outfit that is Italian-themed. Action: spoonacular_API.searchRecipes Action Input: Italian Observation: The API response contains 10 Italian recipes, including Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, and Pappa Al Pomodoro. Thought: I need to find an Italian-themed outfit. Action: Open_AI_Klarna_product_Api.productsUsingGET Action Input: Italian Observation: I found 10 products related to 'Italian' in the API response. These products include Italian Gold Sparkle Perfectina Necklace - Gold, Italian Design Miami Cuban Link Chain Necklace - Gold, Italian Gold Miami Cuban Link Chain Necklace - Gold, Italian Gold Herringbone Necklace - Gold, Italian Gold Claddagh Ring - Gold, Italian Gold Herringbone Chain Necklace - Gold, Garmin QuickFit 22mm Italian Vacchetta Leather Band, Macy's Italian Horn Charm - Gold, Dolce & Gabbana Light Blue Italian Love Pour Homme EdT 1.7 fl oz. Thought: I now know the final answer.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-7
Thought: I now know the final answer. Final Answer: To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, or Pappa Al Pomodoro. > Finished chain. 'To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, Italian Steamed Artichokes, Crispy Italian Cauliflower Poppers Appetizer, or Pappa Al Pomodoro.' Thank you!# natural_language_api_tools[1].run("Tell the LangChain audience to 'enjoy the meal' in Italian, please!")
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
ed7a79af929d-8
"In Italian, you can say 'Buon appetito' to someone to wish them to enjoy their meal. This phrase is commonly used in Italy when someone is about to eat, often at the beginning of a meal. It's similar to saying 'Bon appétit' in French or 'Guten Appetit' in German." previous OpenAPI agents next Pandas Dataframe Agent Contents First, import dependencies and load the LLM Next, load the Natural Language API Toolkits Create the Agent Using Auth + Adding more Endpoints Thank you! By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html
58136f950fdf-0
.ipynb .pdf Python Agent Contents Fibonacci Example Training neural net Python Agent# This notebook showcases an agent designed to write and execute python code to answer a question. from langchain.agents.agent_toolkits import create_python_agent from langchain.tools.python.tool import PythonREPLTool from langchain.python import PythonREPL from langchain.llms.openai import OpenAI agent_executor = create_python_agent( llm=OpenAI(temperature=0, max_tokens=1000), tool=PythonREPLTool(), verbose=True ) Fibonacci Example# This example was created by John Wiseman. agent_executor.run("What is the 10th fibonacci number?") > Entering new AgentExecutor chain... I need to calculate the 10th fibonacci number Action: Python REPL Action Input: def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) Observation: Thought: I need to call the function with 10 as the argument Action: Python REPL Action Input: fibonacci(10) Observation: Thought: I now know the final answer Final Answer: 55 > Finished chain. '55' Training neural net# This example was created by Samee Ur Rehman. agent_executor.run("""Understand, write a single neuron neural network in PyTorch. Take synthetic data for y=2x. Train for 1000 epochs and print every 100 epochs. Return prediction for x = 5""") > Entering new AgentExecutor chain...
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/python.html
58136f950fdf-1
Return prediction for x = 5""") > Entering new AgentExecutor chain... I need to write a neural network in PyTorch and train it on the given data. Action: Python REPL Action Input: import torch # Define the model model = torch.nn.Sequential( torch.nn.Linear(1, 1) ) # Define the loss loss_fn = torch.nn.MSELoss() # Define the optimizer optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # Define the data x_data = torch.tensor([[1.0], [2.0], [3.0], [4.0]]) y_data = torch.tensor([[2.0], [4.0], [6.0], [8.0]]) # Train the model for epoch in range(1000): # Forward pass y_pred = model(x_data) # Compute and print loss loss = loss_fn(y_pred, y_data) if (epoch+1) % 100 == 0: print(f'Epoch {epoch+1}: loss = {loss.item():.4f}') # Zero the gradients optimizer.zero_grad() # Backward pass loss.backward() # Update the weights optimizer.step() Observation: Epoch 100: loss = 0.0013 Epoch 200: loss = 0.0007 Epoch 300: loss = 0.0004 Epoch 400: loss = 0.0002 Epoch 500: loss = 0.0001 Epoch 600: loss = 0.0001 Epoch 700: loss = 0.0000 Epoch 800: loss = 0.0000 Epoch 900: loss = 0.0000 Epoch 1000: loss = 0.0000
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/python.html
58136f950fdf-2
Epoch 900: loss = 0.0000 Epoch 1000: loss = 0.0000 Thought: I now know the final answer Final Answer: The prediction for x = 5 is 10.0. > Finished chain. 'The prediction for x = 5 is 10.0.' previous PowerBI Dataset Agent next SQL Database Agent Contents Fibonacci Example Training neural net By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/python.html