id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
76c3574f986e-17
Asian Pacific American Heritage Month with Google</a></div></div></div><span id="footer"><div style="font-size:10pt"><div style="margin:19px auto;text-align:center" id="WqQANb"><a href="/intl/en/ads/">Advertising</a><a href="/services/">Business Solutions</a><a href="/intl/en/about.html">About Google</a></div></div><p style="font-size:8pt;color:#70757a">&copy; 2023 - <a href="/intl/en/policies/privacy/">Privacy</a> - <a href="/intl/en/policies/terms/">Terms</a></p></span></center><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){window.google.cdo={height:757,width:1440};(function(){var a=window.innerWidth,b=window.innerHeight;if(!a||!b){var c=window.document,d="CSS1Compat"==c.compatMode?c.documentElement:c.body;a=d.clientWidth;b=d.clientHeight}a&&b&&(a!=google.cdo.width||b!=google.cdo.height)&&google.log("","","/client_204?&atyp=i&biw="+a+"&bih="+b+"&ei="+google.kEI);}).call(this);})();</script> <script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){google.xjs={ck:\'xjs.hp.vUsZk7fd8do.L.X.O\',cs:\'ACT90oF8ktm8JGoaZ23megDhHoJku7YaGw\',excm:[]};})();</script> <script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var
https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
76c3574f986e-18
nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var u=\'/xjs/_/js/k\\x3dxjs.hp.en.q0lHXBfs9JY.O/am\\x3dAAAA6AQAUABgAQ/d\\x3d1/ed\\x3d1/rs\\x3dACT90oE3ek6-fjkab6CsTH0wUEUUPhnExg/m\\x3dsb_he,d\';var amd=0;\nvar e=this||self,f=function(c){return c};var h;var n=function(c,g){this.g=g===l?c:""};n.prototype.toString=function(){return this.g+""};var l={};\nfunction p(){var c=u,g=function(){};google.lx=google.stvsc?g:function(){google.timers&&google.timers.load&&google.tick&&google.tick("load","xjsls");var a=document;var b="SCRIPT";"application/xhtml+xml"===a.contentType&&(b=b.toLowerCase());b=a.createElement(b);a=null===c?"null":void 0===c?"undefined":c;if(void 0===h){var d=null;var m=e.trustedTypes;if(m&&m.createPolicy){try{d=m.createPolicy("goog#html",{createHTML:f,createScript:f,createScriptURL:f})}catch(r){e.console&&e.console.error(r.message)}h=\nd}else h=d}a=(d=h)?d.createScriptURL(a):a;a=new n(a,l);b.src=a instanceof n&&a.constructor===n?a.g:"type_error:TrustedResourceUrl";var k,q;(k=(a=null==(q=(k=(b.ownerDocument&&b.ownerDocument.defaultView||window).document).querySelector)?void
https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
76c3574f986e-19
0:q.call(k,"script[nonce]"))?a.nonce||a.getAttribute("nonce")||"":"")&&b.setAttribute("nonce",k);document.body.appendChild(b);google.psa=!0;google.lx=g};google.bx||google.lx()};google.xjsu=u;e._F_jsUrl=u;setTimeout(function(){0<amd?google.caft(function(){return p()},amd):p()},0);})();window._ = window._ || {};window._DumpException = _._DumpException = function(e){throw e;};window._s = window._s || {};_s._DumpException = _._DumpException;window._qs = window._qs || {};_qs._DumpException = _._DumpException;function _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
https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
76c3574f986e-20
Search\\x22,\\x22dym\\x22:\\x22Did you mean:\\x22,\\x22lcky\\x22:\\x22I\\\\u0026#39;m Feeling 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:\\x22C3TIBpTor6RHJfEIn2nbidnhv50\\x22}}\';google.pmc=JSON.parse(pmc);})();</script> </body></html>'
https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
76c3574f986e-21
previous Python REPL next SceneXplain Contents Inside the tool By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/requests.html
372a537fe629-0
.ipynb .pdf File System Tools Contents The FileManagementToolkit Selecting File System Tools File System Tools# LangChain provides tools for interacting with a local file system out of the box. This notebook walks through some of them. Note: these tools are not recommended for use outside a sandboxed environment! First, we’ll import the tools. from langchain.tools.file_management import ( ReadFileTool, CopyFileTool, DeleteFileTool, MoveFileTool, WriteFileTool, ListDirectoryTool, ) from langchain.agents.agent_toolkits import FileManagementToolkit from tempfile import TemporaryDirectory # We'll make a temporary directory to avoid clutter working_directory = TemporaryDirectory() The FileManagementToolkit# If you want to provide all the file tooling to your agent, it’s easy to do so with the toolkit. We’ll pass the temporary directory in as a root directory as a workspace for the LLM. It’s recommended to always pass in a root directory, since without one, it’s easy for the LLM to pollute the working directory, and without one, there isn’t any validation against straightforward prompt injection. toolkit = FileManagementToolkit(root_dir=str(working_directory.name)) # If you don't provide a root_dir, operations will default to the current working directory toolkit.get_tools()
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
372a537fe629-1
toolkit.get_tools() [CopyFileTool(name='copy_file', description='Create a copy of a file in a specified location', args_schema=<class 'langchain.tools.file_management.copy.FileCopyInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), DeleteFileTool(name='file_delete', description='Delete a file', args_schema=<class 'langchain.tools.file_management.delete.FileDeleteInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), FileSearchTool(name='file_search', description='Recursively search for files in a subdirectory that match the regex pattern', args_schema=<class 'langchain.tools.file_management.file_search.FileSearchInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'),
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
372a537fe629-2
MoveFileTool(name='move_file', description='Move or rename a file from one location to another', args_schema=<class 'langchain.tools.file_management.move.FileMoveInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')]
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
372a537fe629-3
Selecting File System Tools# If you only want to select certain tools, you can pass them in as arguments when initializing the toolkit, or you can individually initialize the desired tools. tools = FileManagementToolkit(root_dir=str(working_directory.name), selected_tools=["read_file", "write_file", "list_directory"]).get_tools() tools [ReadFileTool(name='read_file', description='Read file from disk', args_schema=<class 'langchain.tools.file_management.read.ReadFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), WriteFileTool(name='write_file', description='Write file to disk', args_schema=<class 'langchain.tools.file_management.write.WriteFileInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug'), ListDirectoryTool(name='list_directory', description='List files and directories in a specified folder', args_schema=<class 'langchain.tools.file_management.list_dir.DirectoryListingInput'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1156f4350>, root_dir='/var/folders/gf/6rnp_mbx5914kx7qmmh7xzmw0000gn/T/tmpxb8c3aug')] read_tool, write_tool, list_tool = tools write_tool.run({"file_path": "example.txt", "text": "Hello World!"})
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
372a537fe629-4
write_tool.run({"file_path": "example.txt", "text": "Hello World!"}) 'File written successfully to example.txt.' # List files in the working directory list_tool.run({}) 'example.txt' previous DuckDuckGo Search next Google Places Contents The FileManagementToolkit Selecting File System Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/filesystem.html
0ef5093545c1-0
.ipynb .pdf Google Search Contents Number of Results Metadata Results Google Search# This notebook goes over how to use the google search component. First, you need to set up the proper API keys and environment variables. To set it up, create the GOOGLE_API_KEY in the Google Cloud credential console (https://console.cloud.google.com/apis/credentials) and a GOOGLE_CSE_ID using the Programmable Search Enginge (https://programmablesearchengine.google.com/controlpanel/create). Next, it is good to follow the instructions found here. Then we will need to set some environment variables. import os os.environ["GOOGLE_CSE_ID"] = "" os.environ["GOOGLE_API_KEY"] = "" from langchain.tools import Tool from langchain.utilities import GoogleSearchAPIWrapper search = GoogleSearchAPIWrapper() tool = Tool( name = "Google Search", description="Search Google for recent results.", func=search.run ) tool.run("Obama's first name?")
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_search.html
0ef5093545c1-1
"STATE OF HAWAII. 1 Child's First Name. (Type or print). 2. Sex. BARACK. 3. This Birth. CERTIFICATE OF LIVE BIRTH. FILE. NUMBER 151 le. lb. Middle Name. Barack Hussein Obama II is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Jan 19, 2017 ... Jordan Barack Treasure, New York City, born in 2008 ... Jordan Barack Treasure made national news when he was the focus of a New York newspaper\xa0... Portrait of George Washington, the 1st President of the United States ... Portrait of Barack Obama, the 44th President of the United States\xa0... His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Mar 22, 2008 ... Barry Obama decided that he didn't like his nickname. A few of his friends at Occidental College had already begun to call him Barack (his\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama's first name. Miller knew that every answer had to\xa0... Feb 9, 2015 ... Michael Jordan misspelled Barack Obama's first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\xa0... 4 days ago ... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and\xa0..." Number of Results#
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_search.html
0ef5093545c1-2
Number of Results# You can use the k parameter to set the number of results search = GoogleSearchAPIWrapper(k=1) tool = Tool( name = "I'm Feeling Lucky", description="Search Google and return the first result.", func=search.run ) tool.run("python") 'The official home of the Python Programming Language.' ‘The official home of the Python Programming Language.’ Metadata Results# Run query through GoogleSearch and return snippet, title, and link metadata. Snippet: The description of the result. Title: The title of the result. Link: The link to the result. search = GoogleSearchAPIWrapper() def top5_results(query): return search.results(query, 5) tool = Tool( name = "Google Search Snippets", description="Search Google for recent results.", func=top5_results ) previous Google Places next Google Serper API Contents Number of Results Metadata Results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_search.html
8be1e884118f-0
.ipynb .pdf ChatGPT Plugins ChatGPT Plugins# This example shows how to use ChatGPT Plugins within LangChain abstractions. Note 1: This currently only works for plugins with no auth. Note 2: There are almost certainly other ways to do this, this is just a first pass. If you have better ideas, please open a PR! from langchain.chat_models import ChatOpenAI from langchain.agents import load_tools, initialize_agent from langchain.agents import AgentType from langchain.tools import AIPluginTool tool = AIPluginTool.from_plugin_url("https://www.klarna.com/.well-known/ai-plugin.json") llm = ChatOpenAI(temperature=0) tools = load_tools(["requests_all"] ) tools += [tool] agent_chain = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent_chain.run("what t shirts are available in klarna?") > Entering new AgentExecutor chain... I need to check the Klarna Shopping API to see if it has information on available t shirts. Action: KlarnaProducts Action Input: None Observation: Usage Guide: Use the Klarna plugin to get relevant product suggestions for any shopping or researching purpose. The query to be sent should not include stopwords like articles, prepositions and determinants. The api works best when searching for words that are related to products, like their name, brand, model or category. Links will always be returned and should be shown to the user.
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
8be1e884118f-1
OpenAPI Spec: {'openapi': '3.0.1', 'info': {'version': 'v0', 'title': 'Open AI Klarna product Api'}, 'servers': [{'url': 'https://www.klarna.com/us/shopping'}], 'tags': [{'name': 'open-ai-product-endpoint', 'description': 'Open AI Product Endpoint. Query for products.'}], 'paths': {'/public/openai/v0/products': {'get': {'tags': ['open-ai-product-endpoint'], 'summary': 'API for fetching Klarna product information', 'operationId': 'productsUsingGET', 'parameters': [{'name': 'q', 'in': 'query', 'description': 'query, must be between 2 and 100 characters', 'required': True, 'schema': {'type': 'string'}}, {'name': 'size', 'in': 'query', 'description': 'number of products returned', 'required': False, 'schema': {'type': 'integer'}}, {'name': 'budget', 'in': 'query', 'description': 'maximum price of the matching product in local currency, filters results', 'required': False, 'schema': {'type': 'integer'}}], 'responses': {'200': {'description': 'Products found', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/ProductResponse'}}}}, '503': {'description': 'one or more services are unavailable'}}, 'deprecated': False}}}, 'components': {'schemas': {'Product': {'type': 'object', 'properties': {'attributes': {'type': 'array', 'items': {'type': 'string'}}, 'name': {'type': 'string'}, 'price': {'type': 'string'}, 'url': {'type': 'string'}}, 'title': 'Product'}, 'ProductResponse': {'type': 'object', 'properties':
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
8be1e884118f-2
'title': 'Product'}, 'ProductResponse': {'type': 'object', 'properties': {'products': {'type': 'array', 'items': {'$ref': '#/components/schemas/Product'}}}, 'title': 'ProductResponse'}}}}
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
8be1e884118f-3
Thought:I need to use the Klarna Shopping API to search for t shirts. Action: requests_get Action Input: https://www.klarna.com/us/shopping/public/openai/v0/products?q=t%20shirts
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
8be1e884118f-4
Observation: {"products":[{"name":"Lacoste Men's Pack of Plain T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202043025/Clothing/Lacoste-Men-s-Pack-of-Plain-T-Shirts/?utm_source=openai","price":"$26.60","attributes":["Material:Cotton","Target Group:Man","Color:White,Black"]},{"name":"Hanes Men's Ultimate 6pk. Crewneck T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201808270/Clothing/Hanes-Men-s-Ultimate-6pk.-Crewneck-T-Shirts/?utm_source=openai","price":"$13.82","attributes":["Material:Cotton","Target Group:Man","Color:White"]},{"name":"Nike Boy's Jordan Stretch T-shirts","url":"https://www.klarna.com/us/shopping/pl/cl359/3201863202/Children-s-Clothing/Nike-Boy-s-Jordan-Stretch-T-shirts/?utm_source=openai","price":"$14.99","attributes":["Material:Cotton","Color:White,Green","Model:Boy","Size (Small-Large):S,XL,L,M"]},{"name":"Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203028500/Clothing/Polo-Classic-Fit-Cotton-V-Neck-T-Shirts-3-Pack/?utm_source=openai","price":"$29.95","attributes":["Material:Cotton","Target Group:Man","Color:White,Blue,Black"]},{"name":"adidas Comfort T-shirts Men's
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
8be1e884118f-5
Comfort T-shirts Men's 3-pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202640533/Clothing/adidas-Comfort-T-shirts-Men-s-3-pack/?utm_source=openai","price":"$14.99","attributes":["Material:Cotton","Target Group:Man","Color:White,Black","Neckline:Round"]}]}
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
8be1e884118f-6
Thought:The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack. Final Answer: The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack. > Finished chain. "The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack." previous Brave Search next DuckDuckGo Search By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/chatgpt_plugins.html
064b93c530e9-0
.ipynb .pdf YouTubeSearchTool YouTubeSearchTool# This notebook shows how to use a tool to search YouTube Adapted from venuv/langchain_yt_tools #! pip install youtube_search from langchain.tools import YouTubeSearchTool tool = YouTubeSearchTool() tool.run("lex friedman") "['/watch?v=VcVfceTsD0A&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=gPfriiHBBek&pp=ygUMbGV4IGZyaWVkbWFu']" You can also specify the number of results that are returned tool.run("lex friedman,5") "['/watch?v=VcVfceTsD0A&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=YVJ8gTnDC4Y&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=Udh22kuLebg&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=gPfriiHBBek&pp=ygUMbGV4IGZyaWVkbWFu', '/watch?v=L_Guz73e6fw&pp=ygUMbGV4IGZyaWVkbWFu']" previous Wolfram Alpha next Zapier Natural Language Actions API By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/youtube.html
c6e0641c45f9-0
.ipynb .pdf DuckDuckGo Search DuckDuckGo Search# This notebook goes over how to use the duck-duck-go search component. # !pip install duckduckgo-search from langchain.tools import DuckDuckGoSearchRun search = DuckDuckGoSearchRun() search.run("Obama's first name?")
https://python.langchain.com/en/latest/modules/agents/tools/examples/ddg.html
c6e0641c45f9-1
'Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009-17) and the first African American to hold the office. Before winning the presidency, Obama represented Illinois in the U.S. Senate (2005-08). Barack Hussein Obama II (/ b ə ˈ r ɑː k h uː ˈ s eɪ n oʊ ˈ b ɑː m ə / bə-RAHK hoo-SAYN oh-BAH-mə; born August 4, 1961) is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African-American president of the United States. Obama previously served as a U.S. senator representing ... Barack Obama was the first African American president of the United States (2009-17). He oversaw the recovery of the U.S. economy (from the Great Recession of 2008-09) and the enactment of landmark health care reform (the Patient Protection and Affordable Care Act ). In 2009 he was awarded the Nobel Peace Prize. His birth certificate lists his first name as Barack: That\'s how Obama has spelled his name throughout his life. His name derives from a Hebrew name which means "lightning.". The Hebrew word has been transliterated into English in various spellings, including Barak, Buraq, Burack, and Barack. Most common names of U.S. presidents 1789-2021. Published by. Aaron O\'Neill , Jun 21, 2022. The most common first name for a U.S. president is James, followed by John and then William. Six U.S ...' previous
https://python.langchain.com/en/latest/modules/agents/tools/examples/ddg.html
c6e0641c45f9-2
previous ChatGPT Plugins next File System Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/ddg.html
f59b9f603d96-0
.ipynb .pdf Twilio Contents Setup Sending a message Twilio# This notebook goes over how to use the Twilio API wrapper to send a text message. Setup# To use this tool you need to install the Python Twilio package twilio # !pip install twilio You’ll also need to set up a Twilio account and get your credentials. You’ll need your Account String Identifier (SID) and your Auth Token. You’ll also need a number to send messages from. You can either pass these in to the TwilioAPIWrapper as named parameters account_sid, auth_token, from_number, or you can set the environment variables TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM_NUMBER. Sending a message# from langchain.utilities.twilio import TwilioAPIWrapper twilio = TwilioAPIWrapper( # account_sid="foo", # auth_token="bar", # from_number="baz," ) twilio.run("hello world", "+16162904619") previous SerpAPI next Wikipedia Contents Setup Sending a message By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/twilio.html
2aa0001c42bb-0
.ipynb .pdf AWS Lambda API AWS Lambda API# This notebook goes over how to use the AWS Lambda Tool component. AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS), designed to allow developers to build and run applications and services without the need for provisioning or managing servers. This serverless architecture enables you to focus on writing and deploying code, while AWS automatically takes care of scaling, patching, and managing the infrastructure required to run your applications. By including a awslambda in the list of tools provided to an Agent, you can grant your Agent the ability to invoke code running in your AWS Cloud for whatever purposes you need. When an Agent uses the awslambda tool, it will provide an argument of type string which will in turn be passed into the Lambda function via the event parameter. First, you need to install boto3 python package. !pip install boto3 > /dev/null In order for an agent to use the tool, you must provide it with the name and description that match the functionality of you lambda function’s logic. You must also provide the name of your function. Note that because this tool is effectively just a wrapper around the boto3 library, you will need to run aws configure in order to make use of the tool. For more detail, see here from langchain import OpenAI from langchain.agents import load_tools, AgentType llm = OpenAI(temperature=0) tools = load_tools( ["awslambda"], awslambda_tool_name="email-sender", awslambda_tool_description="sends an email with the specified content to [email protected]", function_name="testFunction1" ) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
https://python.langchain.com/en/latest/modules/agents/tools/examples/awslambda.html
2aa0001c42bb-1
agent.run("Send an email to [email protected] saying hello world.") previous ArXiv API Tool next Shell Tool By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/awslambda.html
f5813ba4c868-0
.ipynb .pdf SceneXplain Contents Usage in an Agent SceneXplain# SceneXplain is an ImageCaptioning service accessible through the SceneXplain Tool. To use this tool, you’ll need to make an account and fetch your API Token from the website. Then you can instantiate the tool. import os os.environ["SCENEX_API_KEY"] = "<YOUR_API_KEY>" from langchain.agents import load_tools tools = load_tools(["sceneXplain"]) Or directly instantiate the tool. from langchain.tools import SceneXplainTool tool = SceneXplainTool() Usage in an Agent# The tool can be used in any LangChain agent as follows: from langchain.llms import OpenAI from langchain.agents import initialize_agent from langchain.memory import ConversationBufferMemory llm = OpenAI(temperature=0) memory = ConversationBufferMemory(memory_key="chat_history") agent = initialize_agent( tools, llm, memory=memory, agent="conversational-react-description", verbose=True ) output = agent.run( input=( "What is in this image https://storage.googleapis.com/causal-diffusion.appspot.com/imagePrompts%2F0rw369i5h9t%2Foriginal.png. " "Is it movie or a game? If it is a movie, what is the name of the movie?" ) ) print(output) > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: Image Explainer Action Input: https://storage.googleapis.com/causal-diffusion.appspot.com/imagePrompts%2F0rw369i5h9t%2Foriginal.png
https://python.langchain.com/en/latest/modules/agents/tools/examples/sceneXplain.html
f5813ba4c868-1
Observation: In a charmingly whimsical scene, a young girl is seen braving the rain alongside her furry companion, the lovable Totoro. The two are depicted standing on a bustling street corner, where they are sheltered from the rain by a bright yellow umbrella. The girl, dressed in a cheerful yellow frock, holds onto the umbrella with both hands while gazing up at Totoro with an expression of wonder and delight. Totoro, meanwhile, stands tall and proud beside his young friend, holding his own umbrella aloft to protect them both from the downpour. His furry body is rendered in rich shades of grey and white, while his large ears and wide eyes lend him an endearing charm. In the background of the scene, a street sign can be seen jutting out from the pavement amidst a flurry of raindrops. A sign with Chinese characters adorns its surface, adding to the sense of cultural diversity and intrigue. Despite the dreary weather, there is an undeniable sense of joy and camaraderie in this heartwarming image. Thought: Do I need to use a tool? No AI: This image appears to be a still from the 1988 Japanese animated fantasy film My Neighbor Totoro. The film follows two young girls, Satsuki and Mei, as they explore the countryside and befriend the magical forest spirits, including the titular character Totoro. > Finished chain. This image appears to be a still from the 1988 Japanese animated fantasy film My Neighbor Totoro. The film follows two young girls, Satsuki and Mei, as they explore the countryside and befriend the magical forest spirits, including the titular character Totoro. previous Requests next Search Tools Contents Usage in an Agent By Harrison Chase © Copyright 2023, Harrison Chase.
https://python.langchain.com/en/latest/modules/agents/tools/examples/sceneXplain.html
f5813ba4c868-2
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/sceneXplain.html
00a7c236b2da-0
.ipynb .pdf Python REPL Python REPL# Sometimes, for complex calculations, rather than have an LLM generate the answer directly, it can be better to have the LLM generate code to calculate the answer, and then run that code to get the answer. In order to easily do that, we provide a simple Python REPL to execute commands in. This interface will only return things that are printed - therefore, if you want to use it to calculate an answer, make sure to have it print out the answer. from langchain.agents import Tool from langchain.utilities import PythonREPL python_repl = PythonREPL() python_repl.run("print(1+1)") '2\n' # You can create the tool to pass to an agent repl_tool = Tool( name="python_repl", description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.", func=python_repl.run ) previous PubMed Tool next Requests By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/python.html
5ce817afaa0d-0
.ipynb .pdf Human as a tool Contents Configuring the Input Function Human as a tool# Human are AGI so they can certainly be used as a tool to help out AI agent when it is confused. from langchain.chat_models import ChatOpenAI from langchain.llms import OpenAI from langchain.agents import load_tools, initialize_agent from langchain.agents import AgentType llm = ChatOpenAI(temperature=0.0) math_llm = OpenAI(temperature=0.0) tools = load_tools( ["human", "llm-math"], llm=math_llm, ) agent_chain = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) In the above code you can see the tool takes input directly from command line. You can customize prompt_func and input_func according to your need (as shown below). agent_chain.run("What's my friend Eric's surname?") # Answer with 'Zhu' > Entering new AgentExecutor chain... I don't know Eric's surname, so I should ask a human for guidance. Action: Human Action Input: "What is Eric's surname?" What is Eric's surname? Zhu Observation: Zhu Thought:I now know Eric's surname is Zhu. Final Answer: Eric's surname is Zhu. > Finished chain. "Eric's surname is Zhu." Configuring the Input Function# By default, the HumanInputRun tool uses the python input function to get input from the user. You can customize the input_func to be anything you’d like. For instance, if you want to accept multi-line input, you could do the following: def get_input() -> str:
https://python.langchain.com/en/latest/modules/agents/tools/examples/human_tools.html
5ce817afaa0d-1
def get_input() -> str: print("Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end.") contents = [] while True: try: line = input() except EOFError: break if line == "q": break contents.append(line) return "\n".join(contents) # You can modify the tool when loading tools = load_tools( ["human", "ddg-search"], llm=math_llm, input_func=get_input ) # Or you can directly instantiate the tool from langchain.tools import HumanInputRun tool = HumanInputRun(input_func=get_input) agent_chain = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) agent_chain.run("I need help attributing a quote") > Entering new AgentExecutor chain... I should ask a human for guidance Action: Human Action Input: "Can you help me attribute a quote?" Can you help me attribute a quote? Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end. vini vidi vici q Observation: vini vidi vici Thought:I need to provide more context about the quote Action: Human Action Input: "The quote is 'Veni, vidi, vici'" The quote is 'Veni, vidi, vici' Insert your text. Enter 'q' or press Ctrl-D (or Ctrl-Z on Windows) to end. oh who said it q Observation: oh who said it
https://python.langchain.com/en/latest/modules/agents/tools/examples/human_tools.html
5ce817afaa0d-2
oh who said it q Observation: oh who said it Thought:I can use DuckDuckGo Search to find out who said the quote Action: DuckDuckGo Search Action Input: "Who said 'Veni, vidi, vici'?"
https://python.langchain.com/en/latest/modules/agents/tools/examples/human_tools.html
5ce817afaa0d-3
Observation: Updated on September 06, 2019. "Veni, vidi, vici" is a famous phrase said to have been spoken by the Roman Emperor Julius Caesar (100-44 BCE) in a bit of stylish bragging that impressed many of the writers of his day and beyond. The phrase means roughly "I came, I saw, I conquered" and it could be pronounced approximately Vehnee, Veedee ... Veni, vidi, vici (Classical Latin: [weːniː wiːdiː wiːkiː], Ecclesiastical Latin: [ˈveni ˈvidi ˈvitʃi]; "I came; I saw; I conquered") is a Latin phrase used to refer to a swift, conclusive victory.The phrase is popularly attributed to Julius Caesar who, according to Appian, used the phrase in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short ... veni, vidi, vici Latin quotation from Julius Caesar ve· ni, vi· di, vi· ci ˌwā-nē ˌwē-dē ˈwē-kē ˌvā-nē ˌvē-dē ˈvē-chē : I came, I saw, I conquered Articles Related to veni, vidi, vici 'In Vino Veritas' and Other Latin... Dictionary Entries Near veni, vidi, vici Venite veni, vidi, vici Venizélos See More Nearby Entries Cite this Entry Style The simplest explanation for why veni, vidi, vici is a popular saying is that it comes from Julius Caesar, one of history's most famous figures, and has a simple, strong meaning: I'm powerful and fast. But it's not just the meaning that makes
https://python.langchain.com/en/latest/modules/agents/tools/examples/human_tools.html
5ce817afaa0d-4
simple, strong meaning: I'm powerful and fast. But it's not just the meaning that makes the phrase so powerful. Caesar was a gifted writer, and the phrase makes use of Latin grammar to ... One of the best known and most frequently quoted Latin expression, veni, vidi, vici may be found hundreds of times throughout the centuries used as an expression of triumph. The words are said to have been used by Caesar as he was enjoying a triumph.
https://python.langchain.com/en/latest/modules/agents/tools/examples/human_tools.html
5ce817afaa0d-5
Thought:I now know the final answer Final Answer: Julius Caesar said the quote "Veni, vidi, vici" which means "I came, I saw, I conquered". > Finished chain. 'Julius Caesar said the quote "Veni, vidi, vici" which means "I came, I saw, I conquered".' previous HuggingFace Tools next IFTTT WebHooks Contents Configuring the Input Function By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/human_tools.html
4e24dd503937-0
.ipynb .pdf Google Serper API Contents As part of a Self Ask With Search Chain Obtaining results with metadata Searching for Google Images Searching for Google News Searching for Google Places Google Serper API# This notebook goes over how to use the Google Serper component to search the web. First you need to sign up for a free account at serper.dev and get your api key. import os import pprint os.environ["SERPER_API_KEY"] = "" from langchain.utilities import GoogleSerperAPIWrapper search = GoogleSerperAPIWrapper() search.run("Obama's first name?") 'Barack Hussein Obama II' As part of a Self Ask With Search Chain# os.environ['OPENAI_API_KEY'] = "" from langchain.utilities import GoogleSerperAPIWrapper from langchain.llms.openai import OpenAI from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType llm = OpenAI(temperature=0) search = GoogleSerperAPIWrapper() 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: Current champions Carlos Alcaraz, 2022 men's singles champion. Follow up: Where is Carlos Alcaraz from? Intermediate answer: El Palmar, Spain
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-1
Intermediate answer: El Palmar, Spain So the final answer is: El Palmar, Spain > Finished chain. 'El Palmar, Spain' Obtaining results with metadata# If you would also like to obtain the results in a structured way including metadata. For this we will be using the results method of the wrapper. search = GoogleSerperAPIWrapper() results = search.results("Apple Inc.") pprint.pp(results) {'searchParameters': {'q': 'Apple Inc.', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'search'}, 'knowledgeGraph': {'title': 'Apple', 'type': 'Technology company', 'website': 'http://www.apple.com/', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwGQRv5TjjkycpctY66mOg_e2-npacrmjAb6_jAWhzlzkFE3OTjxyzbA&s=0', 'description': 'Apple Inc. is an American multinational ' 'technology company headquartered in ' 'Cupertino, California. Apple is the ' "world's largest technology company by " 'revenue, with US$394.3 billion in 2022 ' 'revenue. As of March 2023, Apple is the ' "world's biggest...", 'descriptionSource': 'Wikipedia', 'descriptionLink': 'https://en.wikipedia.org/wiki/Apple_Inc.', 'attributes': {'Customer service': '1 (800) 275-2273', 'CEO': 'Tim Cook (Aug 24, 2011–)',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-2
'CEO': 'Tim Cook (Aug 24, 2011–)', 'Headquarters': 'Cupertino, CA', 'Founded': 'April 1, 1976, Los Altos, CA', 'Founders': 'Steve Jobs, Steve Wozniak, ' 'Ronald Wayne, and more', 'Products': 'iPhone, iPad, Apple TV, and ' 'more'}}, 'organic': [{'title': 'Apple', 'link': 'https://www.apple.com/', 'snippet': 'Discover the innovative world of Apple and shop ' 'everything iPhone, iPad, Apple Watch, Mac, and Apple ' 'TV, plus explore accessories, entertainment, ...', 'sitelinks': [{'title': 'Support', 'link': 'https://support.apple.com/'}, {'title': 'iPhone', 'link': 'https://www.apple.com/iphone/'}, {'title': 'Site Map', 'link': 'https://www.apple.com/sitemap/'}, {'title': 'Business', 'link': 'https://www.apple.com/business/'}, {'title': 'Mac', 'link': 'https://www.apple.com/mac/'}, {'title': 'Watch', 'link': 'https://www.apple.com/watch/'}], 'position': 1}, {'title': 'Apple Inc. - Wikipedia', 'link': 'https://en.wikipedia.org/wiki/Apple_Inc.', 'snippet': 'Apple Inc. is an American multinational technology ' 'company headquartered in Cupertino, California. ' "Apple is the world's largest technology company by " 'revenue, ...',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-3
'revenue, ...', 'attributes': {'Products': 'AirPods; Apple Watch; iPad; iPhone; ' 'Mac; Full list', 'Founders': 'Steve Jobs; Steve Wozniak; Ronald ' 'Wayne; Mike Markkula'}, 'sitelinks': [{'title': 'History', 'link': 'https://en.wikipedia.org/wiki/History_of_Apple_Inc.'}, {'title': 'Timeline of Apple Inc. products', 'link': 'https://en.wikipedia.org/wiki/Timeline_of_Apple_Inc._products'}, {'title': 'Litigation involving Apple Inc.', 'link': 'https://en.wikipedia.org/wiki/Litigation_involving_Apple_Inc.'}, {'title': 'Apple Store', 'link': 'https://en.wikipedia.org/wiki/Apple_Store'}], 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRvmB5fT1LjqpZx02UM7IJq0Buoqt0DZs_y0dqwxwSWyP4PIN9FaxuTea0&s', 'position': 2}, {'title': 'Apple Inc. | History, Products, Headquarters, & Facts ' '| Britannica', 'link': 'https://www.britannica.com/topic/Apple-Inc', 'snippet': 'Apple Inc., formerly Apple Computer, Inc., American ' 'manufacturer of personal computers, smartphones, ' 'tablet computers, computer peripherals, and computer ' '...', 'attributes': {'Related People': 'Steve Jobs Steve Wozniak Jony ' 'Ive Tim Cook Angela Ahrendts',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-4
'Ive Tim Cook Angela Ahrendts', 'Date': '1976 - present'}, 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3liELlhrMz3Wpsox29U8jJ3L8qETR0hBWHXbFnwjwQc34zwZvFELst2E&s', 'position': 3}, {'title': 'AAPL: Apple Inc Stock Price Quote - NASDAQ GS - ' 'Bloomberg.com', 'link': 'https://www.bloomberg.com/quote/AAPL:US', 'snippet': 'AAPL:USNASDAQ GS. Apple Inc. COMPANY INFO ; Open. ' '170.09 ; Prev Close. 169.59 ; Volume. 48,425,696 ; ' 'Market Cap. 2.667T ; Day Range. 167.54170.35.', 'position': 4}, {'title': 'Apple Inc. (AAPL) Company Profile & Facts - Yahoo ' 'Finance', 'link': 'https://finance.yahoo.com/quote/AAPL/profile/', 'snippet': 'Apple Inc. designs, manufactures, and markets ' 'smartphones, personal computers, tablets, wearables, ' 'and accessories worldwide. The company offers ' 'iPhone, a line ...', 'position': 5}, {'title': 'Apple Inc. (AAPL) Stock Price, News, Quote & History - ' 'Yahoo Finance', 'link': 'https://finance.yahoo.com/quote/AAPL', 'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, '
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-5
'snippet': 'Find the latest Apple Inc. (AAPL) stock quote, ' 'history, news and other vital information to help ' 'you with your stock trading and investing.', 'position': 6}], 'peopleAlsoAsk': [{'question': 'What does Apple Inc do?', 'snippet': 'Apple Inc. (Apple) designs, manufactures and ' 'markets smartphones, personal\n' 'computers, tablets, wearables and accessories ' 'and sells a range of related\n' 'services.', 'title': 'AAPL.O - | Stock Price & Latest News - Reuters', 'link': 'https://www.reuters.com/markets/companies/AAPL.O/'}, {'question': 'What is the full form of Apple Inc?', 'snippet': '(formerly Apple Computer Inc.) is an American ' 'computer and consumer electronics\n' 'company famous for creating the iPhone, iPad ' 'and Macintosh computers.', 'title': 'What is Apple? An products and history overview ' '- TechTarget', 'link': 'https://www.techtarget.com/whatis/definition/Apple'}, {'question': 'What is Apple Inc iPhone?', 'snippet': 'Apple Inc (Apple) designs, manufactures, and ' 'markets smartphones, tablets,\n' 'personal computers, and wearable devices. The ' 'company also offers software\n' 'applications and related services, ' 'accessories, and third-party digital content.\n' "Apple's product portfolio includes iPhone, " 'iPad, Mac, iPod, Apple Watch, and\n' 'Apple TV.', 'title': 'Apple Inc Company Profile - Apple Inc Overview - '
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-6
'title': 'Apple Inc Company Profile - Apple Inc Overview - ' 'GlobalData', 'link': 'https://www.globaldata.com/company-profile/apple-inc/'}, {'question': 'Who runs Apple Inc?', 'snippet': 'Timothy Donald Cook (born November 1, 1960) is ' 'an American business executive\n' 'who has been the chief executive officer of ' 'Apple Inc. since 2011. Cook\n' "previously served as the company's chief " 'operating officer under its co-founder\n' 'Steve Jobs. He is the first CEO of any Fortune ' '500 company who is openly gay.', 'title': 'Tim Cook - Wikipedia', 'link': 'https://en.wikipedia.org/wiki/Tim_Cook'}], 'relatedSearches': [{'query': 'Who invented the iPhone'}, {'query': 'Apple iPhone'}, {'query': 'History of Apple company PDF'}, {'query': 'Apple company history'}, {'query': 'Apple company introduction'}, {'query': 'Apple India'}, {'query': 'What does Apple Inc own'}, {'query': 'Apple Inc After Steve'}, {'query': 'Apple Watch'}, {'query': 'Apple App Store'}]} Searching for Google Images# We can also query Google Images using this wrapper. For example: search = GoogleSerperAPIWrapper(type="images") results = search.results("Lion") pprint.pp(results) {'searchParameters': {'q': 'Lion', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'images'}, 'images': [{'title': 'Lion - Wikipedia',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-7
'images': [{'title': 'Lion - Wikipedia', 'imageUrl': 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg', 'imageWidth': 1200, 'imageHeight': 900, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRye79ROKwjfb6017jr0iu8Bz2E1KKuHg-A4qINJaspyxkZrkw&amp;s', 'thumbnailWidth': 259, 'thumbnailHeight': 194, 'source': 'Wikipedia', 'domain': 'en.wikipedia.org', 'link': 'https://en.wikipedia.org/wiki/Lion', 'position': 1}, {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica', 'imageUrl': 'https://cdn.britannica.com/55/2155-050-604F5A4A/lion.jpg', 'imageWidth': 754, 'imageHeight': 752, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS3fnDub1GSojI0hJ-ZGS8Tv-hkNNloXh98DOwXZoZ_nUs3GWSd&amp;s', 'thumbnailWidth': 225, 'thumbnailHeight': 224, 'source': 'Encyclopedia Britannica', 'domain': 'www.britannica.com', 'link': 'https://www.britannica.com/animal/lion', 'position': 2},
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-8
'position': 2}, {'title': 'African lion, facts and photos', 'imageUrl': 'https://i.natgeofe.com/n/487a0d69-8202-406f-a6a0-939ed3704693/african-lion.JPG', 'imageWidth': 3072, 'imageHeight': 2043, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTPlTarrtDbyTiEm-VI_PML9VtOTVPuDXJ5ybDf_lN11H2mShk&amp;s', 'thumbnailWidth': 275, 'thumbnailHeight': 183, 'source': 'National Geographic', 'domain': 'www.nationalgeographic.com', 'link': 'https://www.nationalgeographic.com/animals/mammals/facts/african-lion', 'position': 3}, {'title': 'Saint Louis Zoo | African Lion', 'imageUrl': 'https://optimise2.assets-servd.host/maniacal-finch/production/animals/african-lion-01-01.jpg?w=1200&auto=compress%2Cformat&fit=crop&dm=1658933674&s=4b63f926a0f524f2087a8e0613282bdb', 'imageWidth': 1200, 'imageHeight': 1200, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTlewcJ5SwC7yKup6ByaOjTnAFDeoOiMxyJTQaph2W_I3dnks4&amp;s',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-9
'thumbnailWidth': 225, 'thumbnailHeight': 225, 'source': 'St. Louis Zoo', 'domain': 'stlzoo.org', 'link': 'https://stlzoo.org/animals/mammals/carnivores/lion', 'position': 4}, {'title': 'How to Draw a Realistic Lion like an Artist - Studio ' 'Wildlife', 'imageUrl': 'https://studiowildlife.com/wp-content/uploads/2021/10/245528858_183911853822648_6669060845725210519_n.jpg', 'imageWidth': 1431, 'imageHeight': 2048, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTmn5HayVj3wqoBDQacnUtzaDPZzYHSLKUlIEcni6VB8w0mVeA&amp;s', 'thumbnailWidth': 188, 'thumbnailHeight': 269, 'source': 'Studio Wildlife', 'domain': 'studiowildlife.com', 'link': 'https://studiowildlife.com/how-to-draw-a-realistic-lion-like-an-artist/', 'position': 5}, {'title': 'Lion | Characteristics, Habitat, & Facts | Britannica', 'imageUrl': 'https://cdn.britannica.com/29/150929-050-547070A1/lion-Kenya-Masai-Mara-National-Reserve.jpg', 'imageWidth': 1600, 'imageHeight': 1085,
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-10
'imageWidth': 1600, 'imageHeight': 1085, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCqaKY_THr0IBZN8c-2VApnnbuvKmnsWjfrwKoWHFR9w3eN5o&amp;s', 'thumbnailWidth': 273, 'thumbnailHeight': 185, 'source': 'Encyclopedia Britannica', 'domain': 'www.britannica.com', 'link': 'https://www.britannica.com/animal/lion', 'position': 6}, {'title': "Where do lions live? Facts about lions' habitats and " 'other cool facts', 'imageUrl': 'https://www.gannett-cdn.com/-mm-/b2b05a4ab25f4fca0316459e1c7404c537a89702/c=0-0-1365-768/local/-/media/2022/03/16/USATODAY/usatsports/imageForEntry5-ODq.jpg?width=1365&height=768&fit=crop&format=pjpg&auto=webp', 'imageWidth': 1365, 'imageHeight': 768, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTc_4vCHscgvFvYy3PSrtIOE81kNLAfhDK8F3mfOuotL0kUkbs&amp;s', 'thumbnailWidth': 299, 'thumbnailHeight': 168, 'source': 'USA Today',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-11
'thumbnailHeight': 168, 'source': 'USA Today', 'domain': 'www.usatoday.com', 'link': 'https://www.usatoday.com/story/news/2023/01/08/where-do-lions-live-habitat/10927718002/', 'position': 7}, {'title': 'Lion', 'imageUrl': 'https://i.natgeofe.com/k/1d33938b-3d02-4773-91e3-70b113c3b8c7/lion-male-roar_square.jpg', 'imageWidth': 3072, 'imageHeight': 3072, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQqLfnBrBLcTiyTZynHH3FGbBtX2bd1ScwpcuOLnksTyS9-4GM&amp;s', 'thumbnailWidth': 225, 'thumbnailHeight': 225, 'source': 'National Geographic Kids', 'domain': 'kids.nationalgeographic.com', 'link': 'https://kids.nationalgeographic.com/animals/mammals/facts/lion', 'position': 8}, {'title': "Lion | Smithsonian's National Zoo", 'imageUrl': 'https://nationalzoo.si.edu/sites/default/files/styles/1400_scale/public/animals/exhibit/africanlion-005.jpg?itok=6wA745g_', 'imageWidth': 1400, 'imageHeight': 845,
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-12
'imageWidth': 1400, 'imageHeight': 845, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgB3z_D4dMEOWJ7lajJk4XaQSL4DdUvIRj4UXZ0YoE5fGuWuo&amp;s', 'thumbnailWidth': 289, 'thumbnailHeight': 174, 'source': "Smithsonian's National Zoo", 'domain': 'nationalzoo.si.edu', 'link': 'https://nationalzoo.si.edu/animals/lion', 'position': 9}, {'title': "Zoo's New Male Lion Explores Habitat for the First Time " '- Virginia Zoo', 'imageUrl': 'https://virginiazoo.org/wp-content/uploads/2022/04/ZOO_0056-scaled.jpg', 'imageWidth': 2560, 'imageHeight': 2141, 'thumbnailUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDCG7XvXRCwpe_-Vy5mpvrQpVl5q2qwgnDklQhrJpQzObQGz4&amp;s', 'thumbnailWidth': 246, 'thumbnailHeight': 205, 'source': 'Virginia Zoo', 'domain': 'virginiazoo.org', 'link': 'https://virginiazoo.org/zoos-new-male-lion-explores-habitat-for-thefirst-time/', 'position': 10}]} Searching for Google News# We can also query Google News using this wrapper. For example:
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-13
Searching for Google News# We can also query Google News using this wrapper. For example: search = GoogleSerperAPIWrapper(type="news") results = search.results("Tesla Inc.") pprint.pp(results) {'searchParameters': {'q': 'Tesla Inc.', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'news'}, 'news': [{'title': 'ISS recommends Tesla investors vote against re-election ' 'of Robyn Denholm', 'link': 'https://www.reuters.com/business/autos-transportation/iss-recommends-tesla-investors-vote-against-re-election-robyn-denholm-2023-05-04/', 'snippet': 'Proxy advisory firm ISS on Wednesday recommended Tesla ' 'investors vote against re-election of board chair Robyn ' 'Denholm, citing "concerns on...', 'date': '5 mins ago', 'source': 'Reuters', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROdETe_GUyp1e8RHNhaRM8Z_vfxCvdfinZwzL1bT1ZGSYaGTeOojIdBoLevA&s', 'position': 1}, {'title': 'Global companies by market cap: Tesla fell most in April', 'link': 'https://www.reuters.com/markets/global-companies-by-market-cap-tesla-fell-most-april-2023-05-02/', 'snippet': 'Tesla Inc was the biggest loser among top companies by ' 'market capitalisation in April, hit by disappointing ' 'quarterly earnings after it...',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-14
'quarterly earnings after it...', 'date': '1 day ago', 'source': 'Reuters', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ4u4CP8aOdGyRFH6o4PkXi-_eZDeY96vLSag5gDjhKMYf98YBER2cZPbkStQ&s', 'position': 2}, {'title': 'Tesla Wanted an EV Price War. Ford Showed Up.', 'link': 'https://www.bloomberg.com/opinion/articles/2023-05-03/tesla-wanted-an-ev-price-war-ford-showed-up', 'snippet': 'The legacy automaker is paring back the cost of its ' 'Mustang Mach-E model after Tesla discounted its ' 'competing EVs, portending tighter...', 'date': '6 hours ago', 'source': 'Bloomberg.com', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_3Eo4VI0H-nTeIbYc5DaQn5ep7YrWnmhx6pv8XddFgNF5zRC9gEpHfDq8yQ&s', 'position': 3}, {'title': 'Joby Aviation to get investment from Tesla shareholder ' 'Baillie Gifford', 'link': 'https://finance.yahoo.com/news/joby-aviation-investment-tesla-shareholder-204450712.html', 'snippet': 'This comes days after Joby clinched a $55 million ' 'contract extension to deliver up to nine air taxis to '
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-15
'contract extension to deliver up to nine air taxis to ' 'the U.S. Air Force,...', 'date': '4 hours ago', 'source': 'Yahoo Finance', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO0uVn297LI-xryrPNqJ-apUOulj4ohM-xkN4OfmvMOYh1CPdUEBbYx6hviw&s', 'position': 4}, {'title': 'Tesla resumes U.S. orders for a Model 3 version at lower ' 'price, range', 'link': 'https://finance.yahoo.com/news/tesla-resumes-us-orders-model-045736115.html', 'snippet': '(Reuters) -Tesla Inc has resumed taking orders for its ' 'Model 3 long-range vehicle in the United States, the ' "company's website showed late on...", 'date': '19 hours ago', 'source': 'Yahoo Finance', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIZetJ62sQefPfbQ9KKDt6iH7Mc0ylT5t_hpgeeuUkHhJuAx2FOJ4ZTRVDFg&s', 'position': 5}, {'title': 'The Tesla Model 3 Long Range AWD Is Now Available in the ' 'U.S. With 325 Miles of Range', 'link': 'https://www.notateslaapp.com/news/1393/tesla-reopens-orders-for-model-3-long-range-after-months-of-unavailability',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-16
'snippet': 'Tesla has reopened orders for the Model 3 Long Range ' 'RWD, which has been unavailable for months due to high ' 'demand.', 'date': '7 hours ago', 'source': 'Not a Tesla App', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSecrgxZpRj18xIJY-nDHljyP-A4ejEkswa9eq77qhMNrScnVIqe34uql5U4w&s', 'position': 6}, {'title': 'Tesla Cybertruck alpha prototype spotted at the Fremont ' 'factory in new pics and videos', 'link': 'https://www.teslaoracle.com/2023/05/03/tesla-cybertruck-alpha-prototype-interior-and-exterior-spotted-at-the-fremont-factory-in-new-pics-and-videos/', 'snippet': 'A Tesla Cybertruck alpha prototype goes to Fremont, ' 'California for another round of testing before going to ' 'production later this year (pics...', 'date': '14 hours ago', 'source': 'Tesla Oracle', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRO7M5ZLQE-Zo4-_5dv9hNAQZ3wSqfvYCuKqzxHG-M6CgLpwPMMG_ssebdcMg&s', 'position': 7}, {'title': 'Tesla putting facility in new part of country - Austin ' 'Business Journal',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-17
'Business Journal', 'link': 'https://www.bizjournals.com/austin/news/2023/05/02/tesla-leases-building-seattle-area.html', 'snippet': 'Check out what Puget Sound Business Journal has to ' "report about the Austin-based company's real estate " 'footprint in the Pacific Northwest.', 'date': '22 hours ago', 'source': 'The Business Journals', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9kIEHWz1FcHKDUtGQBS0AjmkqtyuBkQvD8kyIY3kpaPrgYaN7I_H2zoOJsA&s', 'position': 8}, {'title': 'Tesla (TSLA) Resumes Orders for Model 3 Long Range After ' 'Backlog', 'link': 'https://www.bloomberg.com/news/articles/2023-05-03/tesla-resumes-orders-for-popular-model-3-long-range-at-47-240', 'snippet': 'Tesla Inc. has resumed taking orders for its Model 3 ' 'Long Range edition with a starting price of $47240, ' 'according to its website.', 'date': '5 hours ago', 'source': 'Bloomberg.com', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTWWIC4VpMTfRvSyqiomODOoLg0xhoBf-Tc1qweKnSuaiTk-Y1wMJZM3jct0w&s', 'position': 9}]}
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-18
'position': 9}]} If you want to only receive news articles published in the last hour, you can do the following: search = GoogleSerperAPIWrapper(type="news", tbs="qdr:h") results = search.results("Tesla Inc.") pprint.pp(results) {'searchParameters': {'q': 'Tesla Inc.', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'news', 'tbs': 'qdr:h'}, 'news': [{'title': 'Oklahoma Gov. Stitt sees growing foreign interest in ' 'investments in ...', 'link': 'https://www.reuters.com/world/us/oklahoma-gov-stitt-sees-growing-foreign-interest-investments-state-2023-05-04/', 'snippet': 'T)), a battery supplier to electric vehicle maker Tesla ' 'Inc (TSLA.O), said on Sunday it is considering building ' 'a battery plant in Oklahoma, its third in...', 'date': '53 mins ago', 'source': 'Reuters', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSTcsXeenqmEKdiekvUgAmqIPR4nlAmgjTkBqLpza-lLfjX1CwB84MoNVj0Q&s', 'position': 1}, {'title': 'Ryder lanza solución llave en mano para vehículos ' 'eléctricos en EU', 'link': 'https://www.tyt.com.mx/nota/ryder-lanza-solucion-llave-en-mano-para-vehiculos-electricos-en-eu',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-19
'snippet': 'Ryder System Inc. presentó RyderElectric+ TM como su ' 'nueva solución llave en mano ... Ryder también tiene ' 'reservados los semirremolques Tesla y continúa...', 'date': '56 mins ago', 'source': 'Revista Transportes y Turismo', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQJhXTQQtjSUZf9YPM235WQhFU5_d7lEA76zB8DGwZfixcgf1_dhPJyKA1Nbw&s', 'position': 2}, {'title': '"I think people can get by with $999 million," Bernie ' 'Sanders tells American Billionaires.', 'link': 'https://thebharatexpressnews.com/i-think-people-can-get-by-with-999-million-bernie-sanders-tells-american-billionaires-heres-how-the-ultra-rich-can-pay-less-income-tax-than-you-legally/', 'snippet': 'The report noted that in 2007 and 2011, Amazon.com Inc. ' 'founder Jeff Bezos “did not pay a dime in federal ... ' 'If you want to bet on Musk, check out Tesla.', 'date': '11 mins ago', 'source': 'THE BHARAT EXPRESS NEWS', 'imageUrl': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR_X9qqSwVFBBdos2CK5ky5IWIE3aJPCQeRYR9O1Jz4t-MjaEYBuwK7AU3AJQ&s', 'position': 3}]}
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-20
'position': 3}]} Some examples of the tbs parameter: qdr:h (past hour) qdr:d (past day) qdr:w (past week) qdr:m (past month) qdr:y (past year) You can specify intermediate time periods by adding a number: qdr:h12 (past 12 hours) qdr:d3 (past 3 days) qdr:w2 (past 2 weeks) qdr:m6 (past 6 months) qdr:m2 (past 2 years) For all supported filters simply go to Google Search, search for something, click on “Tools”, add your date filter and check the URL for “tbs=”. Searching for Google Places# We can also query Google Places using this wrapper. For example: search = GoogleSerperAPIWrapper(type="places") results = search.results("Italian restaurants in Upper East Side") pprint.pp(results) {'searchParameters': {'q': 'Italian restaurants in Upper East Side', 'gl': 'us', 'hl': 'en', 'num': 10, 'type': 'places'}, 'places': [{'position': 1, 'title': "L'Osteria", 'address': '1219 Lexington Ave', 'latitude': 40.777154599999996, 'longitude': -73.9571363, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNjU7BWEq_aYQANBCbX52Kb0lDpd_lFIx5onw40=w92-h92-n-k-no', 'rating': 4.7, 'ratingCount': 91, 'category': 'Italian'},
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-21
'ratingCount': 91, 'category': 'Italian'}, {'position': 2, 'title': "Tony's Di Napoli", 'address': '1081 3rd Ave', 'latitude': 40.7643567, 'longitude': -73.9642373, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNbNv6jZkJ9nyVi60__8c1DQbe_eEbugRAhIYye=w92-h92-n-k-no', 'rating': 4.5, 'ratingCount': 2265, 'category': 'Italian'}, {'position': 3, 'title': 'Caravaggio', 'address': '23 E 74th St', 'latitude': 40.773412799999996, 'longitude': -73.96473379999999, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPDGchokDvppoLfmVEo6X_bWd3Fz0HyxIHTEe9V=w92-h92-n-k-no', 'rating': 4.5, 'ratingCount': 276, 'category': 'Italian'}, {'position': 4, 'title': 'Luna Rossa', 'address': '347 E 85th St', 'latitude': 40.776593999999996, 'longitude': -73.950351,
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-22
'longitude': -73.950351, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNPCpCPuqPAb1Mv6_fOP7cjb8Wu1rbqbk2sMBlh=w92-h92-n-k-no', 'rating': 4.5, 'ratingCount': 140, 'category': 'Italian'}, {'position': 5, 'title': "Paola's", 'address': '1361 Lexington Ave', 'latitude': 40.7822019, 'longitude': -73.9534096, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPJr2Vcx-B6K-GNQa4koOTffggTePz8TKRTnWi3=w92-h92-n-k-no', 'rating': 4.5, 'ratingCount': 344, 'category': 'Italian'}, {'position': 6, 'title': 'Come Prima', 'address': '903 Madison Ave', 'latitude': 40.772124999999996, 'longitude': -73.965012, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNrX19G0NVdtDyMovCQ-M-m0c_gLmIxrWDQAAbz=w92-h92-n-k-no', 'rating': 4.5, 'ratingCount': 176, 'category': 'Italian'}, {'position': 7, 'title': 'Botte UES', 'address': '1606 1st Ave.',
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-23
'address': '1606 1st Ave.', 'latitude': 40.7750785, 'longitude': -73.9504801, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPPN5GXxfH3NDacBc0Pt3uGAInd9OChS5isz9RF=w92-h92-n-k-no', 'rating': 4.4, 'ratingCount': 152, 'category': 'Italian'}, {'position': 8, 'title': 'Piccola Cucina Uptown', 'address': '106 E 60th St', 'latitude': 40.7632468, 'longitude': -73.9689825, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipPifIgzOCD5SjgzzqBzGkdZCBp0MQsK5k7M7znn=w92-h92-n-k-no', 'rating': 4.6, 'ratingCount': 941, 'category': 'Italian'}, {'position': 9, 'title': 'Pinocchio Restaurant', 'address': '300 E 92nd St', 'latitude': 40.781453299999995, 'longitude': -73.9486788, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipNtxlIyEEJHtDtFtTR9nB38S8A2VyMu-mVVz72A=w92-h92-n-k-no', 'rating': 4.5, 'ratingCount': 113,
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
4e24dd503937-24
'rating': 4.5, 'ratingCount': 113, 'category': 'Italian'}, {'position': 10, 'title': 'Barbaresco', 'address': '843 Lexington Ave #1', 'latitude': 40.7654332, 'longitude': -73.9656873, 'thumbnailUrl': 'https://lh5.googleusercontent.com/p/AF1QipMb9FbPuXF_r9g5QseOHmReejxSHgSahPMPJ9-8=w92-h92-n-k-no', 'rating': 4.3, 'ratingCount': 122, 'locationHint': 'In The Touraine', 'category': 'Italian'}]} previous Google Search next Gradio Tools Contents As part of a Self Ask With Search Chain Obtaining results with metadata Searching for Google Images Searching for Google News Searching for Google Places By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html
e20b6d400526-0
.ipynb .pdf Gradio Tools Contents Using a tool Using within an agent Gradio Tools# There are many 1000s of Gradio apps on Hugging Face Spaces. This library puts them at the tips of your LLM’s fingers 🦾 Specifically, gradio-tools is a Python library for converting Gradio apps into tools that can be leveraged by a large language model (LLM)-based agent to complete its task. For example, an LLM could use a Gradio tool to transcribe a voice recording it finds online and then summarize it for you. Or it could use a different Gradio tool to apply OCR to a document on your Google Drive and then answer questions about it. It’s very easy to create you own tool if you want to use a space that’s not one of the pre-built tools. Please see this section of the gradio-tools documentation for information on how to do that. All contributions are welcome! # !pip install gradio_tools Using a tool# from gradio_tools.tools import StableDiffusionTool local_file_path = StableDiffusionTool().langchain.run("Please create a photo of a dog riding a skateboard") local_file_path Loaded as API: https://gradio-client-demos-stable-diffusion.hf.space ✔ Job Status: Status.STARTING eta: None '/Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/examples/b61c1dd9-47e2-46f1-a47c-20d27640993d/tmp4ap48vnm.jpg' from PIL import Image im = Image.open(local_file_path) display(im) Using within an agent# from langchain.agents import initialize_agent from langchain.llms import OpenAI
https://python.langchain.com/en/latest/modules/agents/tools/examples/gradio_tools.html
e20b6d400526-1
from langchain.agents import initialize_agent from langchain.llms import OpenAI from gradio_tools.tools import (StableDiffusionTool, ImageCaptioningTool, StableDiffusionPromptGeneratorTool, TextToVideoTool) from langchain.memory import ConversationBufferMemory llm = OpenAI(temperature=0) memory = ConversationBufferMemory(memory_key="chat_history") tools = [StableDiffusionTool().langchain, ImageCaptioningTool().langchain, StableDiffusionPromptGeneratorTool().langchain, TextToVideoTool().langchain] agent = initialize_agent(tools, llm, memory=memory, agent="conversational-react-description", verbose=True) output = agent.run(input=("Please create a photo of a dog riding a skateboard " "but improve my prompt prior to using an image generator." "Please caption the generated image and create a video for it using the improved prompt.")) Loaded as API: https://gradio-client-demos-stable-diffusion.hf.space ✔ Loaded as API: https://taesiri-blip-2.hf.space ✔ Loaded as API: https://microsoft-promptist.hf.space ✔ Loaded as API: https://damo-vilab-modelscope-text-to-video-synthesis.hf.space ✔ > Entering new AgentExecutor chain... Thought: Do I need to use a tool? Yes Action: StableDiffusionPromptGenerator Action Input: A dog riding a skateboard Job Status: Status.STARTING eta: None Observation: A dog riding a skateboard, digital painting, artstation, concept art, smooth, sharp focus, illustration, art by artgerm and greg rutkowski and alphonse mucha Thought: Do I need to use a tool? Yes Action: StableDiffusion
https://python.langchain.com/en/latest/modules/agents/tools/examples/gradio_tools.html
e20b6d400526-2
Thought: Do I need to use a tool? Yes Action: StableDiffusion Action Input: A dog riding a skateboard, digital painting, artstation, concept art, smooth, sharp focus, illustration, art by artgerm and greg rutkowski and alphonse mucha Job Status: Status.STARTING eta: None Job Status: Status.PROCESSING eta: None Observation: /Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/examples/2e280ce4-4974-4420-8680-450825c31601/tmpfmiz2g1c.jpg Thought: Do I need to use a tool? Yes Action: ImageCaptioner Action Input: /Users/harrisonchase/workplace/langchain/docs/modules/agents/tools/examples/2e280ce4-4974-4420-8680-450825c31601/tmpfmiz2g1c.jpg Job Status: Status.STARTING eta: None Observation: a painting of a dog sitting on a skateboard Thought: Do I need to use a tool? Yes Action: TextToVideo Action Input: a painting of a dog sitting on a skateboard Job Status: Status.STARTING eta: None Due to heavy traffic on this app, the prediction will take approximately 73 seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(damo-vilab/modelscope-text-to-video-synthesis) Job Status: Status.IN_QUEUE eta: 73.89824726581574 Due to heavy traffic on this app, the prediction will take approximately 42 seconds.For faster predictions without waiting in queue, you may duplicate the space using: Client.duplicate(damo-vilab/modelscope-text-to-video-synthesis) Job Status: Status.IN_QUEUE eta: 42.49370198879602
https://python.langchain.com/en/latest/modules/agents/tools/examples/gradio_tools.html
e20b6d400526-3
Job Status: Status.IN_QUEUE eta: 42.49370198879602 Job Status: Status.IN_QUEUE eta: 21.314297944849187 Observation: /var/folders/bm/ylzhm36n075cslb9fvvbgq640000gn/T/tmp5snj_nmzf20_cb3m.mp4 Thought: Do I need to use a tool? No AI: Here is a video of a painting of a dog sitting on a skateboard. > Finished chain. previous Google Serper API next GraphQL tool Contents Using a tool Using within an agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/gradio_tools.html
f50dee506bbf-0
.ipynb .pdf Zapier Natural Language Actions API Contents Zapier Natural Language Actions API Example with Agent Example with SimpleSequentialChain Zapier Natural Language Actions API# Full docs here: https://nla.zapier.com/api/v1/docs Zapier Natural Language Actions gives you access to the 5k+ apps, 20k+ actions on Zapier’s platform through a natural language API interface. NLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets, Microsoft Teams, and thousands more apps: https://zapier.com/apps Zapier NLA handles ALL the underlying API auth and translation from natural language –> underlying API call –> return simplified output for LLMs. The key idea is you, or your users, expose a set of actions via an oauth-like setup window, which you can then query and execute via a REST API. NLA offers both API Key and OAuth for signing NLA API requests. Server-side (API Key): for quickly getting started, testing, and production scenarios where LangChain will only use actions exposed in the developer’s Zapier account (and will use the developer’s connected accounts on Zapier.com) User-facing (Oauth): for production scenarios where you are deploying an end-user facing application and LangChain needs access to end-user’s exposed actions and connected accounts on Zapier.com This quick start will focus on the server-side use case for brevity. Review full docs or reach out to [email protected] for user-facing oauth developer support. This example goes over how to use the Zapier integration with a SimpleSequentialChain, then an Agent. In code, below: import os # get from https://platform.openai.com/ os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "")
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-1
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") # get from https://nla.zapier.com/demo/provider/debug (under User Information, after logging in): os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "") Example with Agent# Zapier tools can be used with an agent. See the example below. from langchain.llms import OpenAI from langchain.agents import initialize_agent from langchain.agents.agent_toolkits import ZapierToolkit from langchain.agents import AgentType from langchain.utilities.zapier import ZapierNLAWrapper ## step 0. expose gmail 'find email' and slack 'send channel message' actions # first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess" # in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first llm = OpenAI(temperature=0) zapier = ZapierNLAWrapper() toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier) agent = initialize_agent(toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("Summarize the last email I received regarding Silicon Valley Bank. Send the summary to the #test-zapier channel in slack.") > Entering new AgentExecutor chain... I need to find the email and summarize it. Action: Gmail: Find Email Action Input: Find the latest email from Silicon Valley Bank
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-2
Action: Gmail: Find Email Action Input: Find the latest email from Silicon Valley Bank Observation: {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "[email protected]", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "[email protected]", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "[email protected]", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"} Thought: I need to summarize the email and send it to the #test-zapier channel in Slack. Action: Slack: Send Channel Message Action Input: Send a slack message to the #test-zapier channel with the text "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild."
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-3
Observation: {"message__text": "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild.", "message__permalink": "https://langchain.slack.com/archives/C04TSGU0RA7/p1678859932375259", "channel": "C04TSGU0RA7", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:58:52Z", "message__bot_profile__icons__image_36": "https://avatars.slack-edge.com/2022-08-02/3888649620612_f864dc1bb794cf7d82b0_36.png", "message__blocks[]block_id": "kdZZ", "message__blocks[]elements[]type": "['rich_text_section']"} Thought: I now know the final answer. Final Answer: I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack. > Finished chain. 'I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.' Example with SimpleSequentialChain# If you need more explicit control, use a chain, like below. from langchain.llms import OpenAI from langchain.chains import LLMChain, TransformChain, SimpleSequentialChain from langchain.prompts import PromptTemplate
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-4
from langchain.prompts import PromptTemplate from langchain.tools.zapier.tool import ZapierNLARunAction from langchain.utilities.zapier import ZapierNLAWrapper ## step 0. expose gmail 'find email' and slack 'send direct message' actions # first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess" # in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first actions = ZapierNLAWrapper().list() ## step 1. gmail find email GMAIL_SEARCH_INSTRUCTIONS = "Grab the latest email from Silicon Valley Bank" def nla_gmail(inputs): action = next((a for a in actions if a["description"].startswith("Gmail: Find Email")), None) return {"email_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["params"]).run(inputs["instructions"])} gmail_chain = TransformChain(input_variables=["instructions"], output_variables=["email_data"], transform=nla_gmail) ## step 2. generate draft reply template = """You are an assisstant who drafts replies to an incoming email. Output draft reply in plain text (not JSON). Incoming email: {email_data} Draft email reply:""" prompt_template = PromptTemplate(input_variables=["email_data"], template=template) reply_chain = LLMChain(llm=OpenAI(temperature=.7), prompt=prompt_template) ## step 3. send draft reply via a slack direct message SLACK_HANDLE = "@Ankush Gola" def nla_slack(inputs):
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-5
SLACK_HANDLE = "@Ankush Gola" def nla_slack(inputs): action = next((a for a in actions if a["description"].startswith("Slack: Send Direct Message")), None) instructions = f'Send this to {SLACK_HANDLE} in Slack: {inputs["draft_reply"]}' return {"slack_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["params"]).run(instructions)} slack_chain = TransformChain(input_variables=["draft_reply"], output_variables=["slack_data"], transform=nla_slack) ## finally, execute overall_chain = SimpleSequentialChain(chains=[gmail_chain, reply_chain, slack_chain], verbose=True) overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS) > Entering new SimpleSequentialChain chain...
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-6
overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS) > Entering new SimpleSequentialChain chain... {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "[email protected]", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "[email protected]", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "[email protected]", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"} Dear Silicon Valley Bridge Bank, Thank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. Best regards, [Your Name]
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-7
Best regards, [Your Name] {"message__text": "Dear Silicon Valley Bridge Bank, \n\nThank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. \n\nBest regards, \n[Your Name]", "message__permalink": "https://langchain.slack.com/archives/D04TKF5BBHU/p1678859968241629", "channel": "D04TKF5BBHU", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:59:28Z", "message__blocks[]block_id": "p7i", "message__blocks[]elements[]elements[]type": "[['text']]", "message__blocks[]elements[]type": "['rich_text_section']"} > Finished chain.
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
f50dee506bbf-8
> Finished chain. '{"message__text": "Dear Silicon Valley Bridge Bank, \\n\\nThank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. \\n\\nBest regards, \\n[Your Name]", "message__permalink": "https://langchain.slack.com/archives/D04TKF5BBHU/p1678859968241629", "channel": "D04TKF5BBHU", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:59:28Z", "message__blocks[]block_id": "p7i", "message__blocks[]elements[]elements[]type": "[[\'text\']]", "message__blocks[]elements[]type": "[\'rich_text_section\']"}' previous YouTubeSearchTool next Agents Contents Zapier Natural Language Actions API Example with Agent Example with SimpleSequentialChain By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html
2d90eb94aa8b-0
.ipynb .pdf ArXiv API Tool Contents The ArXiv API Wrapper ArXiv API Tool# This notebook goes over how to use the arxiv component. First, you need to install arxiv python package. !pip install arxiv from langchain.chat_models import ChatOpenAI from langchain.agents import load_tools, initialize_agent, AgentType llm = ChatOpenAI(temperature=0.0) tools = load_tools( ["arxiv"], ) agent_chain = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) agent_chain.run( "What's the paper 1605.08386 about?", ) > Entering new AgentExecutor chain... I need to use Arxiv to search for the paper. Action: Arxiv Action Input: "1605.08386" Observation: Published: 2016-05-26 Title: Heat-bath random walks with Markov bases Authors: Caprice Stanley, Tobias Windisch Summary: Graphs on lattice points are studied whose edges come from a finite set of allowed moves of arbitrary length. We show that the diameter of these graphs on fibers of a fixed integer matrix can be bounded from above by a constant. We then study the mixing behaviour of heat-bath random walks on these graphs. We also state explicit conditions on the set of moves so that the heat-bath random walk, a generalization of the Glauber dynamics, is an expander in fixed dimension. Thought:The paper is about heat-bath random walks with Markov bases on graphs of lattice points.
https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
2d90eb94aa8b-1
Final Answer: The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points. > Finished chain. 'The paper 1605.08386 is about heat-bath random walks with Markov bases on graphs of lattice points.' The ArXiv API Wrapper# The tool wraps the API Wrapper. Below, we can explore some of the features it provides. 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”. arxiv = ArxivAPIWrapper() 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, the query returns information only about three top articles. docs = arxiv.run("Caprice Stanley") docs
https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
2d90eb94aa8b-2
docs = arxiv.run("Caprice Stanley") docs '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 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.'
https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
2d90eb94aa8b-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 AWS Lambda API Contents The ArXiv API Wrapper By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html
75d4b051935b-0
.ipynb .pdf Brave Search Brave Search# This notebook goes over how to use the Brave Search tool. from langchain.tools import BraveSearch api_key = "..." tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": 3}) tool.run("obama middle name")
https://python.langchain.com/en/latest/modules/agents/tools/examples/brave_search.html
75d4b051935b-1
'[{"title": "Barack Obama - Wikipedia", "link": "https://en.wikipedia.org/wiki/Barack_Obama", "snippet": "Outside of politics, <strong>Obama</strong> has published three bestselling books: Dreams from My Father (1995), The Audacity of Hope (2006) and A Promised Land (2020). Rankings by scholars and historians, in which he has been featured since 2010, place him in the <strong>middle</strong> to upper tier of American presidents."}, {"title": "Obama\'s Middle Name -- My Last Name -- is \'Hussein.\' So?", "link": "https://www.cair.com/cair_in_the_news/obamas-middle-name-my-last-name-is-hussein-so/", "snippet": "Many Americans understand that common names don\\u2019t only come in the form of a \\u201cSmith\\u201d or a \\u201cJohnson.\\u201d Perhaps, they have a neighbor, mechanic or teacher named Hussein. Or maybe they\\u2019ve seen fashion designer Hussein Chalayan in the pages of Vogue or recall <strong>King Hussein</strong>, our ally in the Middle East."}, {"title": "What\'s up with Obama\'s middle name? - Quora", "link": "https://www.quora.com/Whats-up-with-Obamas-middle-name", "snippet": "Answer (1 of 15): A better question would be, \\u201cWhat\\u2019s up with Obama\\u2019s first name?\\u201d President <strong>Barack Hussein Obama</strong>\\u2019s father\\u2019s name was <strong>Barack Hussein Obama</strong>. He was named after his father. Hussein, Obama\\u2019s middle name, is a very common Arabic name, meaning
https://python.langchain.com/en/latest/modules/agents/tools/examples/brave_search.html
75d4b051935b-2
Hussein, Obama\\u2019s middle name, is a very common Arabic name, meaning &quot;good,&quot; &quot;handsome,&quot; or &quot;beautiful.&quot;"}]'
https://python.langchain.com/en/latest/modules/agents/tools/examples/brave_search.html
75d4b051935b-3
previous Bing Search next ChatGPT Plugins By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/brave_search.html
de7451b7f21d-0
.ipynb .pdf PubMed Tool PubMed Tool# This notebook goes over how to use PubMed as a tool PubMed® comprises more than 35 million citations for biomedical literature from MEDLINE, life science journals, and online books. Citations may include links to full text content from PubMed Central and publisher web sites. from langchain.tools import PubmedQueryRun tool = PubmedQueryRun() tool.run("chatgpt") 'Published: <Year>2023</Year><Month>May</Month><Day>31</Day>\nTitle: Dermatology in the wake of an AI revolution: who gets a say?\nSummary: \n\nPublished: <Year>2023</Year><Month>May</Month><Day>30</Day>\nTitle: What is ChatGPT and what do we do with it? Implications of the age of AI for nursing and midwifery practice and education: An editorial.\nSummary: \n\nPublished: <Year>2023</Year><Month>Jun</Month><Day>02</Day>\nTitle: The Impact of ChatGPT on the Nursing Profession: Revolutionizing Patient Care and Education.\nSummary: The nursing field has undergone notable changes over time and is projected to undergo further modifications in the future, owing to the advent of sophisticated technologies and growing healthcare needs. The advent of ChatGPT, an AI-powered language model, is expected to exert a significant influence on the nursing profession, specifically in the domains of patient care and instruction. The present article delves into the ramifications of ChatGPT within the nursing domain and accentuates its capacity and constraints to transform the discipline.' previous OpenWeatherMap API next Python REPL By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/tools/examples/pubmed.html
9e3f0b7b360b-0
.ipynb .pdf Handle Parsing Errors Contents Setup Error Default error handling Custom Error Message Custom Error Function Handle Parsing Errors# Occasionally the LLM cannot determine what step to take because it outputs format in incorrect form to be handled by the output parser. In this case, by default the agent errors. But you can easily control this functionality with handle_parsing_errors! Let’s explore how. Setup# 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 from langchain.agents.types import AGENT_TO_CLASS search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events. You should ask targeted questions" ), ] Error# In this scenario, the agent will error (because it fails to output an Action string) mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action") > Entering new AgentExecutor chain... --------------------------------------------------------------------------- IndexError Traceback (most recent call last) File ~/workplace/langchain/langchain/agents/chat/output_parser.py:21, in ChatOutputParser.parse(self, text) 20 try: ---> 21 action = text.split("```")[1] 22 response = json.loads(action.strip()) IndexError: list index out of range
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
9e3f0b7b360b-1
IndexError: list index out of range During handling of the above exception, another exception occurred: OutputParserException Traceback (most recent call last) Cell In[4], line 1 ----> 1 mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action") File ~/workplace/langchain/langchain/chains/base.py:236, in Chain.run(self, callbacks, *args, **kwargs) 234 if len(args) != 1: 235 raise ValueError("`run` supports only one positional argument.") --> 236 return self(args[0], callbacks=callbacks)[self.output_keys[0]] 238 if kwargs and not args: 239 return self(kwargs, callbacks=callbacks)[self.output_keys[0]] File ~/workplace/langchain/langchain/chains/base.py:140, in Chain.__call__(self, inputs, return_only_outputs, callbacks) 138 except (KeyboardInterrupt, Exception) as e: 139 run_manager.on_chain_error(e) --> 140 raise e 141 run_manager.on_chain_end(outputs) 142 return self.prep_outputs(inputs, outputs, return_only_outputs) File ~/workplace/langchain/langchain/chains/base.py:134, in Chain.__call__(self, inputs, return_only_outputs, callbacks) 128 run_manager = callback_manager.on_chain_start( 129 {"name": self.__class__.__name__}, 130 inputs, 131 ) 132 try: 133 outputs = ( --> 134 self._call(inputs, run_manager=run_manager) 135 if new_arg_supported 136 else self._call(inputs) 137 )
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
9e3f0b7b360b-2
136 else self._call(inputs) 137 ) 138 except (KeyboardInterrupt, Exception) as e: 139 run_manager.on_chain_error(e) File ~/workplace/langchain/langchain/agents/agent.py:947, in AgentExecutor._call(self, inputs, run_manager) 945 # We now enter the agent loop (until it returns something). 946 while self._should_continue(iterations, time_elapsed): --> 947 next_step_output = self._take_next_step( 948 name_to_tool_map, 949 color_mapping, 950 inputs, 951 intermediate_steps, 952 run_manager=run_manager, 953 ) 954 if isinstance(next_step_output, AgentFinish): 955 return self._return( 956 next_step_output, intermediate_steps, run_manager=run_manager 957 ) File ~/workplace/langchain/langchain/agents/agent.py:773, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager) 771 raise_error = False 772 if raise_error: --> 773 raise e 774 text = str(e) 775 if isinstance(self.handle_parsing_errors, bool): File ~/workplace/langchain/langchain/agents/agent.py:762, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager) 756 """Take a single step in the thought-action-observation loop. 757 758 Override this to take control of how the agent makes and acts on choices. 759 """ 760 try:
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
9e3f0b7b360b-3
759 """ 760 try: 761 # Call the LLM to see what to do. --> 762 output = self.agent.plan( 763 intermediate_steps, 764 callbacks=run_manager.get_child() if run_manager else None, 765 **inputs, 766 ) 767 except OutputParserException as e: 768 if isinstance(self.handle_parsing_errors, bool): File ~/workplace/langchain/langchain/agents/agent.py:444, in Agent.plan(self, intermediate_steps, callbacks, **kwargs) 442 full_inputs = self.get_full_inputs(intermediate_steps, **kwargs) 443 full_output = self.llm_chain.predict(callbacks=callbacks, **full_inputs) --> 444 return self.output_parser.parse(full_output) File ~/workplace/langchain/langchain/agents/chat/output_parser.py:26, in ChatOutputParser.parse(self, text) 23 return AgentAction(response["action"], response["action_input"], text) 25 except Exception: ---> 26 raise OutputParserException(f"Could not parse LLM output: {text}") OutputParserException: Could not parse LLM output: I'm sorry, but I cannot provide an answer without an Action. Please provide a valid Action in the format specified above. Default error handling# Handle errors with Invalid or incomplete response mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=True ) mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action") > Entering new AgentExecutor chain... Observation: Invalid or incomplete response
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
9e3f0b7b360b-4
> Entering new AgentExecutor chain... Observation: Invalid or incomplete response Thought: Observation: Invalid or incomplete response Thought:Search for Leo DiCaprio's current girlfriend Action: ``` { "action": "Search", "action_input": "Leo DiCaprio current girlfriend" } ``` Observation: Just Jared on Instagram: “Leonardo DiCaprio & girlfriend Camila Morrone couple up for a lunch date! Thought:Camila Morrone is currently Leo DiCaprio's girlfriend Final Answer: Camila Morrone > Finished chain. 'Camila Morrone' Custom Error Message# You can easily customize the message to use when there are parsing errors mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors="Check your output and make sure it conforms!" ) mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action") > Entering new AgentExecutor chain... Observation: Could not parse LLM output: I'm sorry, but I canno Thought:I need to use the Search tool to find the answer to the question. Action: ``` { "action": "Search", "action_input": "Who is Leo DiCaprio's girlfriend?" } ``` Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week.
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
9e3f0b7b360b-5
Thought:The answer to the question is that Leo DiCaprio's current girlfriend is Gigi Hadid. Final Answer: Gigi Hadid. > Finished chain. 'Gigi Hadid.' Custom Error Function# You can also customize the error to be a function that takes the error in and outputs a string. def _handle_error(error) -> str: return str(error)[:50] mrkl = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=_handle_error ) mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action") > Entering new AgentExecutor chain... Observation: Could not parse LLM output: I'm sorry, but I canno Thought:I need to use the Search tool to find the answer to the question. Action: ``` { "action": "Search", "action_input": "Who is Leo DiCaprio's girlfriend?" } ``` Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spotted getting cozy during a party at New York Fashion Week. Thought:The current girlfriend of Leonardo DiCaprio is Gigi Hadid. Final Answer: Gigi Hadid. > Finished chain. 'Gigi Hadid.' previous How to create ChatGPT Clone next How to access intermediate steps Contents Setup Error Default error handling Custom Error Message Custom Error Function By Harrison Chase
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
9e3f0b7b360b-6
Error Default error handling Custom Error Message Custom Error Function By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html
a88122897464-0
.ipynb .pdf How to combine agents and vectorstores Contents Create the Vectorstore Create the Agent Use the Agent solely as a router Multi-Hop vectorstore reasoning How to combine agents and vectorstores# This notebook covers how to combine agents and vectorstores. The use case for this is that you’ve ingested your data into a vectorstore and want to interact with it in an agentic manner. The recommended method for doing so is to create a RetrievalQA and then use that as a tool in the overall agent. Let’s take a look at doing this below. You can do this with multiple different vectordbs, and use the agent as a way to route between them. There are two different ways of doing this - you can either let the agent use the vectorstores as normal tools, or you can set return_direct=True to really just use the agent as a router. Create the Vectorstore# from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain.llms import OpenAI from langchain.chains import RetrievalQA llm = OpenAI(temperature=0) from pathlib import Path relevant_parts = [] for p in Path(".").absolute().parts: relevant_parts.append(p) if relevant_parts[-3:] == ["langchain", "docs", "modules"]: break doc_path = str(Path(*relevant_parts) / "state_of_the_union.txt") from langchain.document_loaders import TextLoader loader = TextLoader(doc_path) documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings()
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-1
texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = Chroma.from_documents(texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. state_of_union = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=docsearch.as_retriever()) from langchain.document_loaders import WebBaseLoader loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/") docs = loader.load() ruff_texts = text_splitter.split_documents(docs) ruff_db = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff") ruff = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=ruff_db.as_retriever()) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. Create the Agent# # Import things that are needed generically from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.tools import BaseTool from langchain.llms import OpenAI from langchain import LLMMathChain, SerpAPIWrapper tools = [ Tool( name = "State of Union QA System", func=state_of_union.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question." ), Tool( name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question." ), ]
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-2
), ] # Construct the agent. We will use the default agent type here. # See documentation for a full list of options. agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What did biden say about ketanji brown jackson in the state of the union address?") > Entering new AgentExecutor chain... I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address. Action: State of Union QA System Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address? Observation: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. Thought: I now know the final answer Final Answer: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. "Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent.run("Why use ruff over flake8?") > Entering new AgentExecutor chain... I need to find out the advantages of using ruff over flake8 Action: Ruff QA System Action Input: What are the advantages of using ruff over flake8?
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-3
Action Input: What are the advantages of using ruff over flake8? Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. Thought: I now know the final answer Final Answer: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. > Finished chain. 'Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.' Use the Agent solely as a router# You can also set return_direct=True if you intend to use the agent as a router and just want to directly return the result of the RetrievalQAChain.
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-4
Notice that in the above examples the agent did some extra work after querying the RetrievalQAChain. You can avoid that and just return the result directly. tools = [ Tool( name = "State of Union QA System", func=state_of_union.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question.", return_direct=True ), Tool( name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question.", return_direct=True ), ] agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What did biden say about ketanji brown jackson in the state of the union address?") > Entering new AgentExecutor chain... I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address. Action: State of Union QA System Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address? Observation: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence. > Finished chain. " Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence." agent.run("Why use ruff over flake8?") > Entering new AgentExecutor chain... I need to find out the advantages of using ruff over flake8 Action: Ruff QA System
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-5
Action: Ruff QA System Action Input: What are the advantages of using ruff over flake8? Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not. > Finished chain. ' Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.' Multi-Hop vectorstore reasoning# Because vectorstores are easily usable as tools in agents, it is easy to use answer multi-hop questions that depend on vectorstores using the existing agent framework tools = [ Tool( name = "State of Union QA System", func=state_of_union.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question, not referencing any obscure pronouns from the conversation before." ), Tool( name = "Ruff QA System", func=ruff.run,
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-6
name = "Ruff QA System", func=ruff.run, description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question, not referencing any obscure pronouns from the conversation before." ), ] # Construct the agent. We will use the default agent type here. # See documentation for a full list of options. agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses to run over Jupyter Notebooks, and if the president mentioned it in the state of the union. Action: Ruff QA System Action Input: What tool does ruff use to run over Jupyter Notebooks? Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb Thought: I now need to find out if the president mentioned this tool in the state of the union. Action: State of Union QA System Action Input: Did the president mention nbQA in the state of the union? Observation: No, the president did not mention nbQA in the state of the union. Thought: I now know the final answer. Final Answer: No, the president did not mention nbQA in the state of the union. > Finished chain. 'No, the president did not mention nbQA in the state of the union.' previous Agent Executors next
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
a88122897464-7
previous Agent Executors next How to use the async API for Agents Contents Create the Vectorstore Create the Agent Use the Agent solely as a router Multi-Hop vectorstore reasoning By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 11, 2023.
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html
65c15d9b5ced-0
.ipynb .pdf How to use the async API for Agents Contents Serial vs. Concurrent Execution How to use the async API for Agents# LangChain provides async support for Agents by leveraging the asyncio library. Async methods are currently supported for the following Tools: GoogleSerperAPIWrapper, SerpAPIWrapper and LLMMathChain. Async support for other agent tools are on the roadmap. For Tools that have a coroutine implemented (the three mentioned above), the AgentExecutor will await them directly. Otherwise, the AgentExecutor will call the Tool’s func via asyncio.get_event_loop().run_in_executor to avoid blocking the main runloop. You can use arun to call an AgentExecutor asynchronously. Serial vs. Concurrent Execution# In this example, we kick off agents to answer some questions serially vs. concurrently. You can see that concurrent execution significantly speeds this up. import asyncio import time from langchain.agents import initialize_agent, load_tools from langchain.agents import AgentType from langchain.llms import OpenAI from langchain.callbacks.stdout import StdOutCallbackHandler from langchain.callbacks.tracers import LangChainTracer from aiohttp import ClientSession questions = [ "Who won the US Open men's final in 2019? What is his age raised to the 0.334 power?", "Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?", "Who won the most recent formula 1 grand prix? What is their age raised to the 0.23 power?", "Who won the US Open women's final in 2019? What is her age raised to the 0.34 power?", "Who is Beyonce's husband? What is his age raised to the 0.19 power?" ] llm = OpenAI(temperature=0)
https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html