Source code for langchain_community.agent_toolkits.load_tools
# flake8: noqa"""Tools provide access to various resources and services.LangChain has a large ecosystem of integrations with various external resourceslike local and remote file systems, APIs and databases.These integrations allow developers to create versatile applications that combine thepower of LLMs with the ability to access, interact with and manipulate externalresources.When developing an application, developers should inspect the capabilities andpermissions of the tools that underlie the given agent toolkit, and determinewhether permissions of the given toolkit are appropriate for the application.See [Security](https://python.langchain.com/docs/security) for more information."""importwarningsfromtypingimportAny,Dict,List,Optional,Callable,Tuplefrommypy_extensionsimportArg,KwArgfromlangchain_community.tools.arxiv.toolimportArxivQueryRunfromlangchain_community.tools.bing_search.toolimportBingSearchRunfromlangchain_community.tools.dataforseo_api_searchimportDataForSeoAPISearchResultsfromlangchain_community.tools.dataforseo_api_searchimportDataForSeoAPISearchRunfromlangchain_community.tools.ddg_search.toolimportDuckDuckGoSearchRunfromlangchain_community.tools.eleven_labs.text2speechimportElevenLabsText2SpeechToolfromlangchain_community.tools.file_managementimportReadFileToolfromlangchain_community.tools.golden_query.toolimportGoldenQueryRunfromlangchain_community.tools.google_cloud.texttospeechimport(GoogleCloudTextToSpeechTool,)fromlangchain_community.tools.google_finance.toolimportGoogleFinanceQueryRunfromlangchain_community.tools.google_jobs.toolimportGoogleJobsQueryRunfromlangchain_community.tools.google_lens.toolimportGoogleLensQueryRunfromlangchain_community.tools.google_scholar.toolimportGoogleScholarQueryRunfromlangchain_community.tools.google_search.toolimport(GoogleSearchResults,GoogleSearchRun,)fromlangchain_community.tools.google_serper.toolimport(GoogleSerperResults,GoogleSerperRun,)fromlangchain_community.tools.google_trends.toolimportGoogleTrendsQueryRunfromlangchain_community.tools.graphql.toolimportBaseGraphQLToolfromlangchain_community.tools.human.toolimportHumanInputRunfromlangchain_community.tools.memorize.toolimportMemorizefromlangchain_community.tools.merriam_webster.toolimportMerriamWebsterQueryRunfromlangchain_community.tools.metaphor_search.toolimportMetaphorSearchResultsfromlangchain_community.tools.openweathermap.toolimportOpenWeatherMapQueryRunfromlangchain_community.tools.pubmed.toolimportPubmedQueryRunfromlangchain_community.tools.reddit_search.toolimportRedditSearchRunfromlangchain_community.tools.requests.toolimport(RequestsDeleteTool,RequestsGetTool,RequestsPatchTool,RequestsPostTool,RequestsPutTool,)fromlangchain_community.tools.scenexplain.toolimportSceneXplainToolfromlangchain_community.tools.searchapi.toolimportSearchAPIResults,SearchAPIRunfromlangchain_community.tools.searx_search.toolimport(SearxSearchResults,SearxSearchRun,)fromlangchain_community.tools.shell.toolimportShellToolfromlangchain_community.tools.sleep.toolimportSleepToolfromlangchain_community.tools.stackexchange.toolimportStackExchangeToolfromlangchain_community.tools.wikipedia.toolimportWikipediaQueryRunfromlangchain_community.tools.wolfram_alpha.toolimportWolframAlphaQueryRunfromlangchain_community.utilities.arxivimportArxivAPIWrapperfromlangchain_community.utilities.awslambdaimportLambdaWrapperfromlangchain_community.utilities.bing_searchimportBingSearchAPIWrapperfromlangchain_community.utilities.dalle_image_generatorimportDallEAPIWrapperfromlangchain_community.utilities.dataforseo_api_searchimportDataForSeoAPIWrapperfromlangchain_community.utilities.duckduckgo_searchimportDuckDuckGoSearchAPIWrapperfromlangchain_community.utilities.golden_queryimportGoldenQueryAPIWrapperfromlangchain_community.utilities.google_booksimportGoogleBooksAPIWrapperfromlangchain_community.utilities.google_financeimportGoogleFinanceAPIWrapperfromlangchain_community.utilities.google_jobsimportGoogleJobsAPIWrapperfromlangchain_community.utilities.google_lensimportGoogleLensAPIWrapperfromlangchain_community.utilities.google_scholarimportGoogleScholarAPIWrapperfromlangchain_community.utilities.google_searchimportGoogleSearchAPIWrapperfromlangchain_community.utilities.google_serperimportGoogleSerperAPIWrapperfromlangchain_community.utilities.google_trendsimportGoogleTrendsAPIWrapperfromlangchain_community.utilities.graphqlimportGraphQLAPIWrapperfromlangchain_community.utilities.merriam_websterimportMerriamWebsterAPIWrapperfromlangchain_community.utilities.metaphor_searchimportMetaphorSearchAPIWrapperfromlangchain_community.utilities.openweathermapimportOpenWeatherMapAPIWrapperfromlangchain_community.utilities.pubmedimportPubMedAPIWrapperfromlangchain_community.utilities.reddit_searchimportRedditSearchAPIWrapperfromlangchain_community.utilities.requestsimportTextRequestsWrapperfromlangchain_community.utilities.searchapiimportSearchApiAPIWrapperfromlangchain_community.utilities.searx_searchimportSearxSearchWrapperfromlangchain_community.utilities.serpapiimportSerpAPIWrapperfromlangchain_community.utilities.stackexchangeimportStackExchangeAPIWrapperfromlangchain_community.utilities.twilioimportTwilioAPIWrapperfromlangchain_community.utilities.wikipediaimportWikipediaAPIWrapperfromlangchain_community.utilities.wolfram_alphaimportWolframAlphaAPIWrapperfromlangchain_core.callbacksimportBaseCallbackManagerfromlangchain_core.callbacksimportCallbacksfromlangchain_core.language_modelsimportBaseLanguageModelfromlangchain_core.toolsimportBaseTool,Tooldef_get_tools_requests_get()->BaseTool:# Dangerous requests are allowed here, because there's another flag that the user# has to provide in order to actually opt in.# This is a private function and should not be used directly.returnRequestsGetTool(requests_wrapper=TextRequestsWrapper(),allow_dangerous_requests=True)def_get_tools_requests_post()->BaseTool:# Dangerous requests are allowed here, because there's another flag that the user# has to provide in order to actually opt in.# This is a private function and should not be used directly.returnRequestsPostTool(requests_wrapper=TextRequestsWrapper(),allow_dangerous_requests=True)def_get_tools_requests_patch()->BaseTool:# Dangerous requests are allowed here, because there's another flag that the user# has to provide in order to actually opt in.# This is a private function and should not be used directly.returnRequestsPatchTool(requests_wrapper=TextRequestsWrapper(),allow_dangerous_requests=True)def_get_tools_requests_put()->BaseTool:# Dangerous requests are allowed here, because there's another flag that the user# has to provide in order to actually opt in.# This is a private function and should not be used directly.returnRequestsPutTool(requests_wrapper=TextRequestsWrapper(),allow_dangerous_requests=True)def_get_tools_requests_delete()->BaseTool:# Dangerous requests are allowed here, because there's another flag that the user# has to provide in order to actually opt in.# This is a private function and should not be used directly.returnRequestsDeleteTool(requests_wrapper=TextRequestsWrapper(),allow_dangerous_requests=True)def_get_terminal()->BaseTool:returnShellTool()def_get_sleep()->BaseTool:returnSleepTool()_BASE_TOOLS:Dict[str,Callable[[],BaseTool]]={"sleep":_get_sleep,}DANGEROUS_TOOLS={# Tools that contain some level of risk.# Please use with caution and read the documentation of these tools# to understand the risks and how to mitigate them.# Refer to https://python.langchain.com/docs/security# for more information."requests":_get_tools_requests_get,# preserved for backwards compatibility"requests_get":_get_tools_requests_get,"requests_post":_get_tools_requests_post,"requests_patch":_get_tools_requests_patch,"requests_put":_get_tools_requests_put,"requests_delete":_get_tools_requests_delete,"terminal":_get_terminal,}def_get_llm_math(llm:BaseLanguageModel)->BaseTool:try:fromlangchain.chains.llm_math.baseimportLLMMathChainexceptImportError:raiseImportError("LLM Math tools require the library `langchain` to be installed."" Please install it with `pip install langchain`.")returnTool(name="Calculator",description="Useful for when you need to answer questions about math.",func=LLMMathChain.from_llm(llm=llm).run,coroutine=LLMMathChain.from_llm(llm=llm).arun,)def_get_open_meteo_api(llm:BaseLanguageModel)->BaseTool:try:fromlangchain.chains.api.baseimportAPIChainfromlangchain.chains.apiimport(open_meteo_docs,)exceptImportError:raiseImportError("API tools require the library `langchain` to be installed."" Please install it with `pip install langchain`.")chain=APIChain.from_llm_and_api_docs(llm,open_meteo_docs.OPEN_METEO_DOCS,limit_to_domains=["https://api.open-meteo.com/"],)returnTool(name="Open-Meteo-API",description="Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.",func=chain.run,)_LLM_TOOLS:Dict[str,Callable[[BaseLanguageModel],BaseTool]]={"llm-math":_get_llm_math,"open-meteo-api":_get_open_meteo_api,}def_get_news_api(llm:BaseLanguageModel,**kwargs:Any)->BaseTool:news_api_key=kwargs["news_api_key"]try:fromlangchain.chains.api.baseimportAPIChainfromlangchain.chains.apiimport(news_docs,)exceptImportError:raiseImportError("API tools require the library `langchain` to be installed."" Please install it with `pip install langchain`.")chain=APIChain.from_llm_and_api_docs(llm,news_docs.NEWS_DOCS,headers={"X-Api-Key":news_api_key},limit_to_domains=["https://newsapi.org/"],)returnTool(name="News-API",description="Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.",func=chain.run,)def_get_tmdb_api(llm:BaseLanguageModel,**kwargs:Any)->BaseTool:tmdb_bearer_token=kwargs["tmdb_bearer_token"]try:fromlangchain.chains.api.baseimportAPIChainfromlangchain.chains.apiimport(tmdb_docs,)exceptImportError:raiseImportError("API tools require the library `langchain` to be installed."" Please install it with `pip install langchain`.")chain=APIChain.from_llm_and_api_docs(llm,tmdb_docs.TMDB_DOCS,headers={"Authorization":f"Bearer {tmdb_bearer_token}"},limit_to_domains=["https://api.themoviedb.org/"],)returnTool(name="TMDB-API",description="Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.",func=chain.run,)def_get_podcast_api(llm:BaseLanguageModel,**kwargs:Any)->BaseTool:listen_api_key=kwargs["listen_api_key"]try:fromlangchain.chains.api.baseimportAPIChainfromlangchain.chains.apiimport(podcast_docs,)exceptImportError:raiseImportError("API tools require the library `langchain` to be installed."" Please install it with `pip install langchain`.")chain=APIChain.from_llm_and_api_docs(llm,podcast_docs.PODCAST_DOCS,headers={"X-ListenAPI-Key":listen_api_key},limit_to_domains=["https://listen-api.listennotes.com/"],)returnTool(name="Podcast-API",description="Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.",func=chain.run,)def_get_lambda_api(**kwargs:Any)->BaseTool:returnTool(name=kwargs["awslambda_tool_name"],description=kwargs["awslambda_tool_description"],func=LambdaWrapper(**kwargs).run,)def_get_wolfram_alpha(**kwargs:Any)->BaseTool:returnWolframAlphaQueryRun(api_wrapper=WolframAlphaAPIWrapper(**kwargs))def_get_google_search(**kwargs:Any)->BaseTool:returnGoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs))def_get_merriam_webster(**kwargs:Any)->BaseTool:returnMerriamWebsterQueryRun(api_wrapper=MerriamWebsterAPIWrapper(**kwargs))def_get_wikipedia(**kwargs:Any)->BaseTool:returnWikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))def_get_arxiv(**kwargs:Any)->BaseTool:returnArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))def_get_golden_query(**kwargs:Any)->BaseTool:returnGoldenQueryRun(api_wrapper=GoldenQueryAPIWrapper(**kwargs))def_get_pubmed(**kwargs:Any)->BaseTool:returnPubmedQueryRun(api_wrapper=PubMedAPIWrapper(**kwargs))def_get_google_books(**kwargs:Any)->BaseTool:fromlangchain_community.tools.google_booksimportGoogleBooksQueryRunreturnGoogleBooksQueryRun(api_wrapper=GoogleBooksAPIWrapper(**kwargs))def_get_google_jobs(**kwargs:Any)->BaseTool:returnGoogleJobsQueryRun(api_wrapper=GoogleJobsAPIWrapper(**kwargs))def_get_google_lens(**kwargs:Any)->BaseTool:returnGoogleLensQueryRun(api_wrapper=GoogleLensAPIWrapper(**kwargs))def_get_google_serper(**kwargs:Any)->BaseTool:returnGoogleSerperRun(api_wrapper=GoogleSerperAPIWrapper(**kwargs))def_get_google_scholar(**kwargs:Any)->BaseTool:returnGoogleScholarQueryRun(api_wrapper=GoogleScholarAPIWrapper(**kwargs))def_get_google_finance(**kwargs:Any)->BaseTool:returnGoogleFinanceQueryRun(api_wrapper=GoogleFinanceAPIWrapper(**kwargs))def_get_google_trends(**kwargs:Any)->BaseTool:returnGoogleTrendsQueryRun(api_wrapper=GoogleTrendsAPIWrapper(**kwargs))def_get_google_serper_results_json(**kwargs:Any)->BaseTool:returnGoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))def_get_google_search_results_json(**kwargs:Any)->BaseTool:returnGoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs))def_get_searchapi(**kwargs:Any)->BaseTool:returnSearchAPIRun(api_wrapper=SearchApiAPIWrapper(**kwargs))def_get_searchapi_results_json(**kwargs:Any)->BaseTool:returnSearchAPIResults(api_wrapper=SearchApiAPIWrapper(**kwargs))def_get_serpapi(**kwargs:Any)->BaseTool:returnTool(name="Search",description="A search engine. Useful for when you need to answer questions about current events. Input should be a search query.",func=SerpAPIWrapper(**kwargs).run,coroutine=SerpAPIWrapper(**kwargs).arun,)def_get_stackexchange(**kwargs:Any)->BaseTool:returnStackExchangeTool(api_wrapper=StackExchangeAPIWrapper(**kwargs))def_get_dalle_image_generator(**kwargs:Any)->Tool:returnTool("Dall-E-Image-Generator",DallEAPIWrapper(**kwargs).run,"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.",)def_get_twilio(**kwargs:Any)->BaseTool:returnTool(name="Text-Message",description="Useful for when you need to send a text message to a provided phone number.",func=TwilioAPIWrapper(**kwargs).run,)def_get_searx_search(**kwargs:Any)->BaseTool:returnSearxSearchRun(wrapper=SearxSearchWrapper(**kwargs))def_get_searx_search_results_json(**kwargs:Any)->BaseTool:wrapper_kwargs={k:vfork,vinkwargs.items()ifk!="num_results"}returnSearxSearchResults(wrapper=SearxSearchWrapper(**wrapper_kwargs),**kwargs)def_get_bing_search(**kwargs:Any)->BaseTool:returnBingSearchRun(api_wrapper=BingSearchAPIWrapper(**kwargs))def_get_metaphor_search(**kwargs:Any)->BaseTool:returnMetaphorSearchResults(api_wrapper=MetaphorSearchAPIWrapper(**kwargs))def_get_ddg_search(**kwargs:Any)->BaseTool:returnDuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))def_get_human_tool(**kwargs:Any)->BaseTool:returnHumanInputRun(**kwargs)def_get_scenexplain(**kwargs:Any)->BaseTool:returnSceneXplainTool(**kwargs)def_get_graphql_tool(**kwargs:Any)->BaseTool:returnBaseGraphQLTool(graphql_wrapper=GraphQLAPIWrapper(**kwargs))def_get_openweathermap(**kwargs:Any)->BaseTool:returnOpenWeatherMapQueryRun(api_wrapper=OpenWeatherMapAPIWrapper(**kwargs))def_get_dataforseo_api_search(**kwargs:Any)->BaseTool:returnDataForSeoAPISearchRun(api_wrapper=DataForSeoAPIWrapper(**kwargs))def_get_dataforseo_api_search_json(**kwargs:Any)->BaseTool:returnDataForSeoAPISearchResults(api_wrapper=DataForSeoAPIWrapper(**kwargs))def_get_eleven_labs_text2speech(**kwargs:Any)->BaseTool:returnElevenLabsText2SpeechTool(**kwargs)def_get_memorize(llm:BaseLanguageModel,**kwargs:Any)->BaseTool:returnMemorize(llm=llm)# type: ignore[arg-type]def_get_google_cloud_texttospeech(**kwargs:Any)->BaseTool:returnGoogleCloudTextToSpeechTool(**kwargs)def_get_file_management_tool(**kwargs:Any)->BaseTool:returnReadFileTool(**kwargs)def_get_reddit_search(**kwargs:Any)->BaseTool:returnRedditSearchRun(api_wrapper=RedditSearchAPIWrapper(**kwargs))_EXTRA_LLM_TOOLS:Dict[str,Tuple[Callable[[Arg(BaseLanguageModel,"llm"),KwArg(Any)],BaseTool],List[str]],]={"news-api":(_get_news_api,["news_api_key"]),"tmdb-api":(_get_tmdb_api,["tmdb_bearer_token"]),"podcast-api":(_get_podcast_api,["listen_api_key"]),"memorize":(_get_memorize,[]),}_EXTRA_OPTIONAL_TOOLS:Dict[str,Tuple[Callable[[KwArg(Any)],BaseTool],List[str]]]={"wolfram-alpha":(_get_wolfram_alpha,["wolfram_alpha_appid"]),"google-search":(_get_google_search,["google_api_key","google_cse_id"]),"google-search-results-json":(_get_google_search_results_json,["google_api_key","google_cse_id","num_results"],),"searx-search-results-json":(_get_searx_search_results_json,["searx_host","engines","num_results","aiosession"],),"bing-search":(_get_bing_search,["bing_subscription_key","bing_search_url"]),"metaphor-search":(_get_metaphor_search,["metaphor_api_key"]),"ddg-search":(_get_ddg_search,[]),"google-books":(_get_google_books,["google_books_api_key"]),"google-lens":(_get_google_lens,["serp_api_key"]),"google-serper":(_get_google_serper,["serper_api_key","aiosession"]),"google-scholar":(_get_google_scholar,["top_k_results","hl","lr","serp_api_key"],),"google-finance":(_get_google_finance,["serp_api_key"],),"google-trends":(_get_google_trends,["serp_api_key"],),"google-jobs":(_get_google_jobs,["serp_api_key"],),"google-serper-results-json":(_get_google_serper_results_json,["serper_api_key","aiosession"],),"searchapi":(_get_searchapi,["searchapi_api_key","aiosession"]),"searchapi-results-json":(_get_searchapi_results_json,["searchapi_api_key","aiosession"],),"serpapi":(_get_serpapi,["serpapi_api_key","aiosession"]),"dalle-image-generator":(_get_dalle_image_generator,["openai_api_key"]),"twilio":(_get_twilio,["account_sid","auth_token","from_number"]),"searx-search":(_get_searx_search,["searx_host","engines","aiosession"]),"merriam-webster":(_get_merriam_webster,["merriam_webster_api_key"]),"wikipedia":(_get_wikipedia,["top_k_results","lang"]),"arxiv":(_get_arxiv,["top_k_results","load_max_docs","load_all_available_meta"],),"golden-query":(_get_golden_query,["golden_api_key"]),"pubmed":(_get_pubmed,["top_k_results"]),"human":(_get_human_tool,["prompt_func","input_func"]),"awslambda":(_get_lambda_api,["awslambda_tool_name","awslambda_tool_description","function_name"],),"stackexchange":(_get_stackexchange,[]),"sceneXplain":(_get_scenexplain,[]),"graphql":(_get_graphql_tool,["graphql_endpoint","custom_headers","fetch_schema_from_transport"],),"openweathermap-api":(_get_openweathermap,["openweathermap_api_key"]),"dataforseo-api-search":(_get_dataforseo_api_search,["api_login","api_password","aiosession"],),"dataforseo-api-search-json":(_get_dataforseo_api_search_json,["api_login","api_password","aiosession"],),"eleven_labs_text2speech":(_get_eleven_labs_text2speech,["elevenlabs_api_key"]),"google_cloud_texttospeech":(_get_google_cloud_texttospeech,[]),"read_file":(_get_file_management_tool,[]),"reddit_search":(_get_reddit_search,["reddit_client_id","reddit_client_secret","reddit_user_agent"],),}def_handle_callbacks(callback_manager:Optional[BaseCallbackManager],callbacks:Callbacks)->Callbacks:ifcallback_managerisnotNone:warnings.warn("callback_manager is deprecated. Please use callbacks instead.",DeprecationWarning,)ifcallbacksisnotNone:raiseValueError("Cannot specify both callback_manager and callbacks arguments.")returncallback_managerreturncallbacks
[docs]defload_huggingface_tool(task_or_repo_id:str,model_repo_id:Optional[str]=None,token:Optional[str]=None,remote:bool=False,**kwargs:Any,)->BaseTool:"""Loads a tool from the HuggingFace Hub. Args: task_or_repo_id: Task or model repo id. model_repo_id: Optional model repo id. Defaults to None. token: Optional token. Defaults to None. remote: Optional remote. Defaults to False. kwargs: Additional keyword arguments. Returns: A tool. Raises: ImportError: If the required libraries are not installed. NotImplementedError: If multimodal outputs or inputs are not supported. """try:fromtransformersimportload_toolexceptImportError:raiseImportError("HuggingFace tools require the libraries `transformers>=4.29.0`"" and `huggingface_hub>=0.14.1` to be installed."" Please install it with"" `pip install --upgrade transformers huggingface_hub`.")hf_tool=load_tool(task_or_repo_id,model_repo_id=model_repo_id,token=token,remote=remote,**kwargs,)outputs=hf_tool.outputsifset(outputs)!={"text"}:raiseNotImplementedError("Multimodal outputs not supported yet.")inputs=hf_tool.inputsifset(inputs)!={"text"}:raiseNotImplementedError("Multimodal inputs not supported yet.")returnTool.from_function(hf_tool.__call__,name=hf_tool.name,description=hf_tool.description)
[docs]defraise_dangerous_tools_exception(name:str)->None:raiseValueError(f"{name} is a dangerous tool. You cannot use it without opting in ""by setting allow_dangerous_tools to True. ""Most tools have some inherit risk to them merely because they are "'allowed to interact with the "real world".'"Please refer to LangChain security guidelines ""to https://python.langchain.com/docs/security.""Some tools have been designated as dangerous because they pose ""risk that is not intuitively obvious. For example, a tool that ""allows an agent to make requests to the web, can also be used ""to make requests to a server that is only accessible from the ""server hosting the code.""Again, all tools carry some risk, and it's your responsibility to ""understand which tools you're using and the risks associated with ""them.")
[docs]defload_tools(tool_names:List[str],llm:Optional[BaseLanguageModel]=None,callbacks:Callbacks=None,allow_dangerous_tools:bool=False,**kwargs:Any,)->List[BaseTool]:"""Load tools based on their name. Tools allow agents to interact with various resources and services like APIs, databases, file systems, etc. Please scope the permissions of each tools to the minimum required for the application. For example, if an application only needs to read from a database, the database tool should not be given write permissions. Moreover consider scoping the permissions to only allow accessing specific tables and impose user-level quota for limiting resource usage. Please read the APIs of the individual tools to determine which configuration they support. See [Security](https://python.langchain.com/docs/security) for more information. Args: tool_names: name of tools to load. llm: An optional language model may be needed to initialize certain tools. Defaults to None. callbacks: Optional callback manager or list of callback handlers. If not provided, default global callback manager will be used. allow_dangerous_tools: Optional flag to allow dangerous tools. Tools that contain some level of risk. Please use with caution and read the documentation of these tools to understand the risks and how to mitigate them. Refer to https://python.langchain.com/docs/security for more information. Please note that this list may not be fully exhaustive. It is your responsibility to understand which tools you're using and the risks associated with them. Defaults to False. kwargs: Additional keyword arguments. Returns: List of tools. Raises: ValueError: If the tool name is unknown. ValueError: If the tool requires an LLM to be provided. ValueError: If the tool requires some parameters that were not provided. ValueError: If the tool is a dangerous tool and allow_dangerous_tools is False. """tools=[]callbacks=_handle_callbacks(callback_manager=kwargs.get("callback_manager"),callbacks=callbacks)fornameintool_names:ifnameinDANGEROUS_TOOLSandnotallow_dangerous_tools:raise_dangerous_tools_exception(name)ifnamein{"requests"}:warnings.warn("tool name `requests` is deprecated - ""please use `requests_all` or specify the requests method")ifname=="requests_all":# expand requests into various methodsifnotallow_dangerous_tools:raise_dangerous_tools_exception(name)requests_method_tools=[_toolfor_toolinDANGEROUS_TOOLSif_tool.startswith("requests_")]tool_names.extend(requests_method_tools)elifnamein_BASE_TOOLS:tools.append(_BASE_TOOLS[name]())elifnameinDANGEROUS_TOOLS:tools.append(DANGEROUS_TOOLS[name]())elifnamein_LLM_TOOLS:ifllmisNone:raiseValueError(f"Tool {name} requires an LLM to be provided")tool=_LLM_TOOLS[name](llm)tools.append(tool)elifnamein_EXTRA_LLM_TOOLS:ifllmisNone:raiseValueError(f"Tool {name} requires an LLM to be provided")_get_llm_tool_func,extra_keys=_EXTRA_LLM_TOOLS[name]missing_keys=set(extra_keys).difference(kwargs)ifmissing_keys:raiseValueError(f"Tool {name} requires some parameters that were not "f"provided: {missing_keys}")sub_kwargs={k:kwargs[k]forkinextra_keys}tool=_get_llm_tool_func(llm=llm,**sub_kwargs)tools.append(tool)elifnamein_EXTRA_OPTIONAL_TOOLS:_get_tool_func,extra_keys=_EXTRA_OPTIONAL_TOOLS[name]sub_kwargs={k:kwargs[k]forkinextra_keysifkinkwargs}tool=_get_tool_func(**sub_kwargs)tools.append(tool)else:raiseValueError(f"Got unknown tool {name}")ifcallbacksisnotNone:fortoolintools:tool.callbacks=callbacksreturntools
[docs]defget_all_tool_names()->List[str]:"""Get a list of all possible tool names."""return(list(_BASE_TOOLS)+list(_EXTRA_OPTIONAL_TOOLS)+list(_EXTRA_LLM_TOOLS)+list(_LLM_TOOLS)+list(DANGEROUS_TOOLS))