id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
59
127
1fdbd6154f14-0
.ipynb .pdf Tool Input Schema Tool Input Schema# By default, tools infer the argument schema by inspecting the function signature. For more strict requirements, custom input schema can be specified, along with custom validation logic. from typing import Any, Dict from langchain.agents import AgentType, initialize_agent from langchain.llms import OpenAI from langchain.tools.requests.tool import RequestsGetTool, TextRequestsWrapper from pydantic import BaseModel, Field, root_validator llm = OpenAI(temperature=0) !pip install tldextract > /dev/null [notice] A new release of pip is available: 23.0.1 -> 23.1 [notice] To update, run: pip install --upgrade pip import tldextract _APPROVED_DOMAINS = { "langchain", "wikipedia", } class ToolInputSchema(BaseModel): url: str = Field(...) @root_validator def validate_query(cls, values: Dict[str, Any]) -> Dict: url = values["url"] domain = tldextract.extract(url).domain if domain not in _APPROVED_DOMAINS: raise ValueError(f"Domain {domain} is not on the approved list:" f" {sorted(_APPROVED_DOMAINS)}") return values tool = RequestsGetTool(args_schema=ToolInputSchema, requests_wrapper=TextRequestsWrapper()) agent = initialize_agent([tool], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False) # This will succeed, since there aren't any arguments that will be triggered during validation answer = agent.run("What's the main title on langchain.com?") print(answer)
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/tool_input_validation.html
1fdbd6154f14-1
print(answer) The main title of langchain.com is "LANG CHAIN 🦜️🔗 Official Home Page" agent.run("What's the main title on google.com?") --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) Cell In[7], line 1 ----> 1 agent.run("What's the main title on google.com?") File ~/code/lc/lckg/langchain/chains/base.py:213, in Chain.run(self, *args, **kwargs) 211 if len(args) != 1: 212 raise ValueError("`run` supports only one positional argument.") --> 213 return self(args[0])[self.output_keys[0]] 215 if kwargs and not args: 216 return self(kwargs)[self.output_keys[0]] File ~/code/lc/lckg/langchain/chains/base.py:116, in Chain.__call__(self, inputs, return_only_outputs) 114 except (KeyboardInterrupt, Exception) as e: 115 self.callback_manager.on_chain_error(e, verbose=self.verbose) --> 116 raise e 117 self.callback_manager.on_chain_end(outputs, verbose=self.verbose) 118 return self.prep_outputs(inputs, outputs, return_only_outputs) File ~/code/lc/lckg/langchain/chains/base.py:113, in Chain.__call__(self, inputs, return_only_outputs) 107 self.callback_manager.on_chain_start( 108 {"name": self.__class__.__name__}, 109 inputs, 110 verbose=self.verbose, 111 ) 112 try: --> 113 outputs = self._call(inputs) 114 except (KeyboardInterrupt, Exception) as e:
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/tool_input_validation.html
1fdbd6154f14-2
114 except (KeyboardInterrupt, Exception) as e: 115 self.callback_manager.on_chain_error(e, verbose=self.verbose) File ~/code/lc/lckg/langchain/agents/agent.py:792, in AgentExecutor._call(self, inputs) 790 # We now enter the agent loop (until it returns something). 791 while self._should_continue(iterations, time_elapsed): --> 792 next_step_output = self._take_next_step( 793 name_to_tool_map, color_mapping, inputs, intermediate_steps 794 ) 795 if isinstance(next_step_output, AgentFinish): 796 return self._return(next_step_output, intermediate_steps) File ~/code/lc/lckg/langchain/agents/agent.py:695, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps) 693 tool_run_kwargs["llm_prefix"] = "" 694 # We then call the tool on the tool input to get an observation --> 695 observation = tool.run( 696 agent_action.tool_input, 697 verbose=self.verbose, 698 color=color, 699 **tool_run_kwargs, 700 ) 701 else: 702 tool_run_kwargs = self.agent.tool_run_logging_kwargs() File ~/code/lc/lckg/langchain/tools/base.py:110, in BaseTool.run(self, tool_input, verbose, start_color, color, **kwargs) 101 def run( 102 self, 103 tool_input: Union[str, Dict], (...) 107 **kwargs: Any, 108 ) -> str:
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/tool_input_validation.html
1fdbd6154f14-3
107 **kwargs: Any, 108 ) -> str: 109 """Run the tool.""" --> 110 run_input = self._parse_input(tool_input) 111 if not self.verbose and verbose is not None: 112 verbose_ = verbose File ~/code/lc/lckg/langchain/tools/base.py:71, in BaseTool._parse_input(self, tool_input) 69 if issubclass(input_args, BaseModel): 70 key_ = next(iter(input_args.__fields__.keys())) ---> 71 input_args.parse_obj({key_: tool_input}) 72 # Passing as a positional argument is more straightforward for 73 # backwards compatability 74 return tool_input File ~/code/lc/lckg/.venv/lib/python3.11/site-packages/pydantic/main.py:526, in pydantic.main.BaseModel.parse_obj() File ~/code/lc/lckg/.venv/lib/python3.11/site-packages/pydantic/main.py:341, in pydantic.main.BaseModel.__init__() ValidationError: 1 validation error for ToolInputSchema __root__ Domain google is not on the approved list: ['langchain', 'wikipedia'] (type=value_error) previous Multi-Input Tools next Human-in-the-loop Tool Validation By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/tool_input_validation.html
b23ed91ac55a-0
.ipynb .pdf Human-in-the-loop Tool Validation Contents Adding Human Approval Configuring Human Approval Human-in-the-loop Tool Validation# This walkthrough demonstrates how to add Human validation to any Tool. We’ll do this using the HumanApprovalCallbackhandler. Let’s suppose we need to make use of the ShellTool. Adding this tool to an automated flow poses obvious risks. Let’s see how we could enforce manual human approval of inputs going into this tool. Note: We generally recommend against using the ShellTool. There’s a lot of ways to misuse it, and it’s not required for most use cases. We employ it here only for demonstration purposes. from langchain.callbacks import HumanApprovalCallbackHandler from langchain.tools import ShellTool tool = ShellTool() print(tool.run('echo Hello World!')) Hello World! Adding Human Approval# Adding the default HumanApprovalCallbackHandler to the tool will make it so that a user has to manually approve every input to the tool before the command is actually executed. tool = ShellTool(callbacks=[HumanApprovalCallbackHandler()]) print(tool.run("ls /usr")) Do you approve of the following input? Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no. ls /usr yes X11 X11R6 bin lib libexec local sbin share standalone print(tool.run("ls /private")) Do you approve of the following input? Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no. ls /private no --------------------------------------------------------------------------- HumanRejectedException Traceback (most recent call last) Cell In[17], line 1 ----> 1 print(tool.run("ls /private"))
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-1
----> 1 print(tool.run("ls /private")) File ~/langchain/langchain/tools/base.py:257, in BaseTool.run(self, tool_input, verbose, start_color, color, callbacks, **kwargs) 255 # TODO: maybe also pass through run_manager is _run supports kwargs 256 new_arg_supported = signature(self._run).parameters.get("run_manager") --> 257 run_manager = callback_manager.on_tool_start( 258 {"name": self.name, "description": self.description}, 259 tool_input if isinstance(tool_input, str) else str(tool_input), 260 color=start_color, 261 **kwargs, 262 ) 263 try: 264 tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input) File ~/langchain/langchain/callbacks/manager.py:672, in CallbackManager.on_tool_start(self, serialized, input_str, run_id, parent_run_id, **kwargs) 669 if run_id is None: 670 run_id = uuid4() --> 672 _handle_event( 673 self.handlers, 674 "on_tool_start", 675 "ignore_agent", 676 serialized, 677 input_str, 678 run_id=run_id, 679 parent_run_id=self.parent_run_id, 680 **kwargs, 681 ) 683 return CallbackManagerForToolRun( 684 run_id, self.handlers, self.inheritable_handlers, self.parent_run_id 685 ) File ~/langchain/langchain/callbacks/manager.py:157, in _handle_event(handlers, event_name, ignore_condition_name, *args, **kwargs)
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-2
155 except Exception as e: 156 if handler.raise_error: --> 157 raise e 158 logging.warning(f"Error in {event_name} callback: {e}") File ~/langchain/langchain/callbacks/manager.py:139, in _handle_event(handlers, event_name, ignore_condition_name, *args, **kwargs) 135 try: 136 if ignore_condition_name is None or not getattr( 137 handler, ignore_condition_name 138 ): --> 139 getattr(handler, event_name)(*args, **kwargs) 140 except NotImplementedError as e: 141 if event_name == "on_chat_model_start": File ~/langchain/langchain/callbacks/human.py:48, in HumanApprovalCallbackHandler.on_tool_start(self, serialized, input_str, run_id, parent_run_id, **kwargs) 38 def on_tool_start( 39 self, 40 serialized: Dict[str, Any], (...) 45 **kwargs: Any, 46 ) -> Any: 47 if self._should_check(serialized) and not self._approve(input_str): ---> 48 raise HumanRejectedException( 49 f"Inputs {input_str} to tool {serialized} were rejected." 50 ) HumanRejectedException: Inputs ls /private to tool {'name': 'terminal', 'description': 'Run shell commands on this MacOS machine.'} were rejected. Configuring Human Approval# Let’s suppose we have an agent that takes in multiple tools, and we want it to only trigger human approval requests on certain tools and certain inputs. We can configure out callback handler to do just this. from langchain.agents import load_tools
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-3
from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.llms import OpenAI def _should_check(serialized_obj: dict) -> bool: # Only require approval on ShellTool. return serialized_obj.get("name") == "terminal" def _approve(_input: str) -> bool: if _input == "echo 'Hello World'": return True msg = ( "Do you approve of the following input? " "Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no." ) msg += "\n\n" + _input + "\n" resp = input(msg) return resp.lower() in ("yes", "y") callbacks = [HumanApprovalCallbackHandler(should_check=_should_check, approve=_approve)] llm = OpenAI(temperature=0) tools = load_tools(["wikipedia", "llm-math", "terminal"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, ) agent.run("It's 2023 now. How many years ago did Konrad Adenauer become Chancellor of Germany.", callbacks=callbacks) 'Konrad Adenauer became Chancellor of Germany in 1949, 74 years ago.' agent.run("print 'Hello World' in the terminal", callbacks=callbacks) 'Hello World' agent.run("list all directories in /private", callbacks=callbacks) Do you approve of the following input? Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no. ls /private no ---------------------------------------------------------------------------
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-4
ls /private no --------------------------------------------------------------------------- HumanRejectedException Traceback (most recent call last) Cell In[39], line 1 ----> 1 agent.run("list all directories in /private", callbacks=callbacks) File ~/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 ~/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 ~/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 ) 138 except (KeyboardInterrupt, Exception) as e: 139 run_manager.on_chain_error(e)
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-5
139 run_manager.on_chain_error(e) File ~/langchain/langchain/agents/agent.py:953, in AgentExecutor._call(self, inputs, run_manager) 951 # We now enter the agent loop (until it returns something). 952 while self._should_continue(iterations, time_elapsed): --> 953 next_step_output = self._take_next_step( 954 name_to_tool_map, 955 color_mapping, 956 inputs, 957 intermediate_steps, 958 run_manager=run_manager, 959 ) 960 if isinstance(next_step_output, AgentFinish): 961 return self._return( 962 next_step_output, intermediate_steps, run_manager=run_manager 963 ) File ~/langchain/langchain/agents/agent.py:820, in AgentExecutor._take_next_step(self, name_to_tool_map, color_mapping, inputs, intermediate_steps, run_manager) 818 tool_run_kwargs["llm_prefix"] = "" 819 # We then call the tool on the tool input to get an observation --> 820 observation = tool.run( 821 agent_action.tool_input, 822 verbose=self.verbose, 823 color=color, 824 callbacks=run_manager.get_child() if run_manager else None, 825 **tool_run_kwargs, 826 ) 827 else: 828 tool_run_kwargs = self.agent.tool_run_logging_kwargs() File ~/langchain/langchain/tools/base.py:257, in BaseTool.run(self, tool_input, verbose, start_color, color, callbacks, **kwargs)
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-6
255 # TODO: maybe also pass through run_manager is _run supports kwargs 256 new_arg_supported = signature(self._run).parameters.get("run_manager") --> 257 run_manager = callback_manager.on_tool_start( 258 {"name": self.name, "description": self.description}, 259 tool_input if isinstance(tool_input, str) else str(tool_input), 260 color=start_color, 261 **kwargs, 262 ) 263 try: 264 tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input) File ~/langchain/langchain/callbacks/manager.py:672, in CallbackManager.on_tool_start(self, serialized, input_str, run_id, parent_run_id, **kwargs) 669 if run_id is None: 670 run_id = uuid4() --> 672 _handle_event( 673 self.handlers, 674 "on_tool_start", 675 "ignore_agent", 676 serialized, 677 input_str, 678 run_id=run_id, 679 parent_run_id=self.parent_run_id, 680 **kwargs, 681 ) 683 return CallbackManagerForToolRun( 684 run_id, self.handlers, self.inheritable_handlers, self.parent_run_id 685 ) File ~/langchain/langchain/callbacks/manager.py:157, in _handle_event(handlers, event_name, ignore_condition_name, *args, **kwargs) 155 except Exception as e: 156 if handler.raise_error: --> 157 raise e 158 logging.warning(f"Error in {event_name} callback: {e}")
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
b23ed91ac55a-7
158 logging.warning(f"Error in {event_name} callback: {e}") File ~/langchain/langchain/callbacks/manager.py:139, in _handle_event(handlers, event_name, ignore_condition_name, *args, **kwargs) 135 try: 136 if ignore_condition_name is None or not getattr( 137 handler, ignore_condition_name 138 ): --> 139 getattr(handler, event_name)(*args, **kwargs) 140 except NotImplementedError as e: 141 if event_name == "on_chat_model_start": File ~/langchain/langchain/callbacks/human.py:48, in HumanApprovalCallbackHandler.on_tool_start(self, serialized, input_str, run_id, parent_run_id, **kwargs) 38 def on_tool_start( 39 self, 40 serialized: Dict[str, Any], (...) 45 **kwargs: Any, 46 ) -> Any: 47 if self._should_check(serialized) and not self._approve(input_str): ---> 48 raise HumanRejectedException( 49 f"Inputs {input_str} to tool {serialized} were rejected." 50 ) HumanRejectedException: Inputs ls /private to tool {'name': 'terminal', 'description': 'Run shell commands on this MacOS machine.'} were rejected. previous Tool Input Schema next Tools as OpenAI Functions Contents Adding Human Approval Configuring Human Approval By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/human_approval.html
244a11d1ae0c-0
.ipynb .pdf Defining Custom Tools Contents Completely New Tools - String Input and Output Tool dataclass Subclassing the BaseTool class Using the tool decorator Custom Structured Tools StructuredTool dataclass Subclassing the BaseTool Using the decorator Modify existing tools Defining the priorities among Tools Using tools to return directly Handling Tool Errors Defining Custom Tools# When constructing your own agent, you will need to provide it with a list of Tools that it can use. Besides the actual function that is called, the Tool consists of several components: name (str), is required and must be unique within a set of tools provided to an agent description (str), is optional but recommended, as it is used by an agent to determine tool use return_direct (bool), defaults to False args_schema (Pydantic BaseModel), is optional but recommended, can be used to provide more information (e.g., few-shot examples) or validation for expected parameters. There are two main ways to define a tool, we will cover both in the example below. # Import things that are needed generically from langchain import LLMMathChain, SerpAPIWrapper from langchain.agents import AgentType, initialize_agent from langchain.chat_models import ChatOpenAI from langchain.tools import BaseTool, StructuredTool, Tool, tool Initialize the LLM to use for the agent. llm = ChatOpenAI(temperature=0) Completely New Tools - String Input and Output# The simplest tools accept a single query string and return a string output. If your tool function requires multiple arguments, you might want to skip down to the StructuredTool section below. There are two ways to do this: either by using the Tool dataclass, or by subclassing the BaseTool class. Tool dataclass#
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-1
Tool dataclass# The ‘Tool’ dataclass wraps functions that accept a single string input and returns a string output. # Load the tool configs that are needed. search = SerpAPIWrapper() llm_math_chain = LLMMathChain(llm=llm, verbose=True) tools = [ Tool.from_function( func=search.run, name = "Search", description="useful for when you need to answer questions about current events" # coroutine= ... <- you can specify an async method if desired as well ), ] /Users/wfh/code/lc/lckg/langchain/chains/llm_math/base.py:50: UserWarning: Directly instantiating an LLMMathChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method. warnings.warn( You can also define a custom `args_schema`` to provide more information about inputs. from pydantic import BaseModel, Field class CalculatorInput(BaseModel): question: str = Field() tools.append( Tool.from_function( func=llm_math_chain.run, name="Calculator", description="useful for when you need to answer questions about math", args_schema=CalculatorInput # coroutine= ... <- you can specify an async method if desired as well ) ) # 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("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain...
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-2
> Entering new AgentExecutor chain... I need to find out Leo DiCaprio's girlfriend's name and her age Action: Search Action Input: "Leo DiCaprio girlfriend" Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his "age bracket" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani. Thought:I still need to find out his current girlfriend's name and age 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:Now that I know his girlfriend's name is Camila Morrone, I need to find her current age Action: Search Action Input: "Camila Morrone age" Observation: 25 years Thought:Now that I have her age, I need to calculate her age raised to the 0.43 power Action: Calculator Action Input: 25^(0.43) > Entering new LLMMathChain chain... 25^(0.43)```text 25**(0.43) ``` ...numexpr.evaluate("25**(0.43)")... Answer: 3.991298452658078 > Finished chain. Observation: Answer: 3.991298452658078 Thought:I now know the final answer Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99. > Finished chain. "Camila Morrone's current age raised to the 0.43 power is approximately 3.99." Subclassing the BaseTool class#
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-3
Subclassing the BaseTool class# You can also directly subclass BaseTool. This is useful if you want more control over the instance variables or if you want to propagate callbacks to nested chains or other tools. from typing import Optional, Type from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun class CustomSearchTool(BaseTool): name = "custom_search" description = "useful for when you need to answer questions about current events" def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" return search.run(query) async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str: """Use the tool asynchronously.""" raise NotImplementedError("custom_search does not support async") class CustomCalculatorTool(BaseTool): name = "Calculator" description = "useful for when you need to answer questions about math" args_schema: Type[BaseModel] = CalculatorInput def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" return llm_math_chain.run(query) async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str: """Use the tool asynchronously.""" raise NotImplementedError("Calculator does not support async") tools = [CustomSearchTool(), CustomCalculatorTool()] agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-4
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to use custom_search to find out who Leo DiCaprio's girlfriend is, and then use the Calculator to raise her age to the 0.43 power. Action: custom_search Action Input: "Leo DiCaprio girlfriend" Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his "age bracket" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani. Thought:I need to find out the current age of Eden Polani. Action: custom_search Action Input: "Eden Polani age" Observation: 19 years old Thought:Now I can use the Calculator to raise her age to the 0.43 power. Action: Calculator Action Input: 19 ^ 0.43 > Entering new LLMMathChain chain... 19 ^ 0.43```text 19 ** 0.43 ``` ...numexpr.evaluate("19 ** 0.43")... Answer: 3.547023357958959 > Finished chain. Observation: Answer: 3.547023357958959 Thought:I now know the final answer. Final Answer: 3.547023357958959 > Finished chain. '3.547023357958959' Using the tool decorator#
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-5
'3.547023357958959' Using the tool decorator# To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a string as the first argument. Additionally, the decorator will use the function’s docstring as the tool’s description. from langchain.tools import tool @tool def search_api(query: str) -> str: """Searches the API for the query.""" return f"Results for query {query}" search_api You can also provide arguments like the tool name and whether to return directly. @tool("search", return_direct=True) def search_api(query: str) -> str: """Searches the API for the query.""" return "Results" search_api Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bd66310>, coroutine=None) You can also provide args_schema to provide more information about the argument class SearchInput(BaseModel): query: str = Field(description="should be a search query") @tool("search", return_direct=True, args_schema=SearchInput) def search_api(query: str) -> str: """Searches the API for the query.""" return "Results" search_api
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-6
"""Searches the API for the query.""" return "Results" search_api Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class '__main__.SearchInput'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bcf0ee0>, coroutine=None) Custom Structured Tools# If your functions require more structured arguments, you can use the StructuredTool class directly, or still subclass the BaseTool class. StructuredTool dataclass# To dynamically generate a structured tool from a given function, the fastest way to get started is with StructuredTool.from_function(). import requests from langchain.tools import StructuredTool def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str: """Sends a POST request to the given url with the given body and parameters.""" result = requests.post(url, json=body, params=parameters) return f"Status: {result.status_code} - {result.text}" tool = StructuredTool.from_function(post_message) Subclassing the BaseTool# The BaseTool automatically infers the schema from the _run method’s signature. from typing import Optional, Type from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun class CustomSearchTool(BaseTool): name = "custom_search" description = "useful for when you need to answer questions about current events"
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-7
description = "useful for when you need to answer questions about current events" def _run(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" search_wrapper = SerpAPIWrapper(params={"engine": engine, "gl": gl, "hl": hl}) return search_wrapper.run(query) async def _arun(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str: """Use the tool asynchronously.""" raise NotImplementedError("custom_search does not support async") # You can provide a custom args schema to add descriptions or custom validation class SearchSchema(BaseModel): query: str = Field(description="should be a search query") engine: str = Field(description="should be a search engine") gl: str = Field(description="should be a country code") hl: str = Field(description="should be a language code") class CustomSearchTool(BaseTool): name = "custom_search" description = "useful for when you need to answer questions about current events" args_schema: Type[SearchSchema] = SearchSchema def _run(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" search_wrapper = SerpAPIWrapper(params={"engine": engine, "gl": gl, "hl": hl}) return search_wrapper.run(query)
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-8
return search_wrapper.run(query) async def _arun(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str: """Use the tool asynchronously.""" raise NotImplementedError("custom_search does not support async") Using the decorator# The tool decorator creates a structured tool automatically if the signature has multiple arguments. import requests from langchain.tools import tool @tool def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str: """Sends a POST request to the given url with the given body and parameters.""" result = requests.post(url, json=body, params=parameters) return f"Status: {result.status_code} - {result.text}" Modify existing tools# Now, we show how to load existing tools and modify them directly. In the example below, we do something really simple and change the Search tool to have the name Google Search. from langchain.agents import load_tools tools = load_tools(["serpapi", "llm-math"], llm=llm) tools[0].name = "Google Search" agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?") > Entering new AgentExecutor chain... I need to find out Leo DiCaprio's girlfriend's name and her age. Action: Google Search Action Input: "Leo DiCaprio girlfriend"
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-9
Action: Google Search Action Input: "Leo DiCaprio girlfriend" Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his "age bracket" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani. Thought:I still need to find out his current girlfriend's name and her age. Action: Google Search Action Input: "Leo DiCaprio current girlfriend age" Observation: Leonardo DiCaprio has been linked with 19-year-old model Eden Polani, continuing the rumour that he doesn't date any women over the age of ... Thought:I need to find out the age of Eden Polani. Action: Calculator Action Input: 19^(0.43) Observation: Answer: 3.547023357958959 Thought:I now know the final answer. Final Answer: The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55. > Finished chain. "The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55." Defining the priorities among Tools# When you made a Custom tool, you may want the Agent to use the custom tool more than normal tools. For example, you made a custom tool, which gets information on music from your database. When a user wants information on songs, You want the Agent to use the custom tool more than the normal Search tool. But the Agent might prioritize a normal Search tool. This can be accomplished by adding a statement such as Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?' to the description.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-10
An example is below. # Import things that are needed generically from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain.llms import OpenAI from langchain import LLMMathChain, SerpAPIWrapper search = SerpAPIWrapper() tools = [ Tool( name = "Search", func=search.run, description="useful for when you need to answer questions about current events" ), Tool( name="Music Search", func=lambda x: "'All I Want For Christmas Is You' by Mariah Carey.", #Mock Function description="A Music search engine. Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?'", ) ] agent = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("what is the most famous song of christmas") > Entering new AgentExecutor chain... I should use a music search engine to find the answer Action: Music Search Action Input: most famous song of christmas'All I Want For Christmas Is You' by Mariah Carey. I now know the final answer Final Answer: 'All I Want For Christmas Is You' by Mariah Carey. > Finished chain. "'All I Want For Christmas Is You' by Mariah Carey." Using tools to return directly# Often, it can be desirable to have a tool output returned directly to the user, if it’s called. You can do this easily with LangChain by setting the return_direct flag for a tool to be True. llm_math_chain = LLMMathChain(llm=llm) tools = [
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-11
llm_math_chain = LLMMathChain(llm=llm) tools = [ Tool( name="Calculator", func=llm_math_chain.run, description="useful for when you need to answer questions about math", return_direct=True ) ] llm = OpenAI(temperature=0) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("whats 2**.12") > Entering new AgentExecutor chain... I need to calculate this Action: Calculator Action Input: 2**.12Answer: 1.086734862526058 > Finished chain. 'Answer: 1.086734862526058' Handling Tool Errors# When a tool encounters an error and the exception is not caught, the agent will stop executing. If you want the agent to continue execution, you can raise a ToolException and set handle_tool_error accordingly. When ToolException is thrown, the agent will not stop working, but will handle the exception according to the handle_tool_error variable of the tool, and the processing result will be returned to the agent as observation, and printed in red. You can set handle_tool_error to True, set it a unified string value, or set it as a function. If it’s set as a function, the function should take a ToolException as a parameter and return a str value. Please note that only raising a ToolException won’t be effective. You need to first set the handle_tool_error of the tool because its default value is False. from langchain.schema import ToolException from langchain import SerpAPIWrapper from langchain.agents import AgentType, initialize_agent from langchain.chat_models import ChatOpenAI from langchain.tools import Tool
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-12
from langchain.chat_models import ChatOpenAI from langchain.tools import Tool from langchain.chat_models import ChatOpenAI def _handle_error(error:ToolException) -> str: return "The following errors occurred during tool execution:" + error.args[0]+ "Please try another tool." def search_tool1(s: str):raise ToolException("The search tool1 is not available.") def search_tool2(s: str):raise ToolException("The search tool2 is not available.") search_tool3 = SerpAPIWrapper() description="useful for when you need to answer questions about current events.You should give priority to using it." tools = [ Tool.from_function( func=search_tool1, name="Search_tool1", description=description, handle_tool_error=True, ), Tool.from_function( func=search_tool2, name="Search_tool2", description=description, handle_tool_error=_handle_error, ), Tool.from_function( func=search_tool3.run, name="Search_tool3", description="useful for when you need to answer questions about current events", ), ] agent = initialize_agent( tools, ChatOpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, ) agent.run("Who is Leo DiCaprio's girlfriend?") > Entering new AgentExecutor chain... I should use Search_tool1 to find recent news articles about Leo DiCaprio's personal life. Action: Search_tool1 Action Input: "Leo DiCaprio girlfriend" Observation: The search tool1 is not available. Thought:I should try using Search_tool2 instead. Action: Search_tool2
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
244a11d1ae0c-13
Thought:I should try using Search_tool2 instead. Action: Search_tool2 Action Input: "Leo DiCaprio girlfriend" Observation: The following errors occurred during tool execution:The search tool2 is not available.Please try another tool. Thought:I should try using Search_tool3 as a last resort. Action: Search_tool3 Action Input: "Leo DiCaprio girlfriend" Observation: Leonardo DiCaprio and Gigi Hadid were recently spotted at a pre-Oscars party, sparking interest once again in their rumored romance. The Revenant actor and the model first made headlines when they were spotted together at a New York Fashion Week afterparty in September 2022. Thought:Based on the information from Search_tool3, it seems that Gigi Hadid is currently rumored to be Leo DiCaprio's girlfriend. Final Answer: Gigi Hadid is currently rumored to be Leo DiCaprio's girlfriend. > Finished chain. "Gigi Hadid is currently rumored to be Leo DiCaprio's girlfriend." previous Getting Started next Multi-Input Tools Contents Completely New Tools - String Input and Output Tool dataclass Subclassing the BaseTool class Using the tool decorator Custom Structured Tools StructuredTool dataclass Subclassing the BaseTool Using the decorator Modify existing tools Defining the priorities among Tools Using tools to return directly Handling Tool Errors By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/custom_tools.html
b3e708726df4-0
.ipynb .pdf Tools as OpenAI Functions Tools as OpenAI Functions# This notebook goes over how to use LangChain tools as OpenAI functions. from langchain.chat_models import ChatOpenAI from langchain.schema import HumanMessage model = ChatOpenAI(model="gpt-3.5-turbo-0613") from langchain.tools import MoveFileTool, format_tool_to_openai_function tools = [MoveFileTool()] functions = [format_tool_to_openai_function(t) for t in tools] message = model.predict_messages([HumanMessage(content='move file foo to bar')], functions=functions) message AIMessage(content='', additional_kwargs={'function_call': {'name': 'move_file', 'arguments': '{\n "source_path": "foo",\n "destination_path": "bar"\n}'}}, example=False) message.additional_kwargs['function_call'] {'name': 'move_file', 'arguments': '{\n "source_path": "foo",\n "destination_path": "bar"\n}'} previous Human-in-the-loop Tool Validation next Apify By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/tools_as_openai_functions.html
f1de38e13416-0
.md .pdf Getting Started Contents List of Tools Getting Started# Tools are functions that agents can use to interact with the world. These tools can be generic utilities (e.g. search), other chains, or even other agents. Currently, tools can be loaded with the following snippet: from langchain.agents import load_tools tool_names = [...] tools = load_tools(tool_names) Some tools (e.g. chains, agents) may require a base LLM to use to initialize them. In that case, you can pass in an LLM as well: from langchain.agents import load_tools tool_names = [...] llm = ... tools = load_tools(tool_names, llm=llm) Below is a list of all supported tools and relevant information: Tool Name: The name the LLM refers to the tool by. Tool Description: The description of the tool that is passed to the LLM. Notes: Notes about the tool that are NOT passed to the LLM. Requires LLM: Whether this tool requires an LLM to be initialized. (Optional) Extra Parameters: What extra parameters are required to initialize this tool. List of Tools# python_repl Tool Name: Python REPL Tool Description: A Python shell. Use this to execute python commands. Input should be a valid python command. If you expect output it should be printed out. Notes: Maintains state. Requires LLM: No serpapi Tool Name: Search Tool Description: A search engine. Useful for when you need to answer questions about current events. Input should be a search query. Notes: Calls the Serp API and then parses results. Requires LLM: No wolfram-alpha Tool Name: Wolfram Alpha
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/getting_started.html
f1de38e13416-1
Requires LLM: No wolfram-alpha Tool Name: Wolfram Alpha Tool Description: A wolfram alpha search engine. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query. Notes: Calls the Wolfram Alpha API and then parses results. Requires LLM: No Extra Parameters: wolfram_alpha_appid: The Wolfram Alpha app id. requests Tool Name: Requests Tool Description: A portal to the internet. Use this when you need to get specific content from a site. Input should be a specific url, and the output will be all the text on that page. Notes: Uses the Python requests module. Requires LLM: No terminal Tool Name: Terminal Tool Description: Executes commands in a terminal. Input should be valid commands, and the output will be any output from running that command. Notes: Executes commands with subprocess. Requires LLM: No pal-math Tool Name: PAL-MATH Tool Description: A language model that is excellent at solving complex word math problems. Input should be a fully worded hard word math problem. Notes: Based on this paper. Requires LLM: Yes pal-colored-objects Tool Name: PAL-COLOR-OBJ Tool Description: A language model that is wonderful at reasoning about position and the color attributes of objects. Input should be a fully worded hard reasoning problem. Make sure to include all information about the objects AND the final question you want to answer. Notes: Based on this paper. Requires LLM: Yes llm-math Tool Name: Calculator Tool Description: Useful for when you need to answer questions about math. Notes: An instance of the LLMMath chain. Requires LLM: Yes open-meteo-api Tool Name: Open Meteo API
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/getting_started.html
f1de38e13416-2
Requires LLM: Yes open-meteo-api Tool Name: Open Meteo API Tool 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. Notes: A natural language connection to the Open Meteo API (https://api.open-meteo.com/), specifically the /v1/forecast endpoint. Requires LLM: Yes news-api Tool Name: News API Tool 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. Notes: A natural language connection to the News API (https://newsapi.org), specifically the /v2/top-headlines endpoint. Requires LLM: Yes Extra Parameters: news_api_key (your API key to access this endpoint) tmdb-api Tool Name: TMDB API Tool 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. Notes: A natural language connection to the TMDB API (https://api.themoviedb.org/3), specifically the /search/movie endpoint. Requires LLM: Yes Extra Parameters: tmdb_bearer_token (your Bearer Token to access this endpoint - note that this is different from the API key) google-search Tool Name: Search Tool Description: A wrapper around Google Search. Useful for when you need to answer questions about current events. Input should be a search query. Notes: Uses the Google Custom Search API Requires LLM: No Extra Parameters: google_api_key, google_cse_id For more information on this, see this page searx-search Tool Name: Search
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/getting_started.html
f1de38e13416-3
For more information on this, see this page searx-search Tool Name: Search Tool Description: A wrapper around SearxNG meta search engine. Input should be a search query. Notes: SearxNG is easy to deploy self-hosted. It is a good privacy friendly alternative to Google Search. Uses the SearxNG API. Requires LLM: No Extra Parameters: searx_host google-serper Tool Name: Search Tool Description: A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query. Notes: Calls the serper.dev Google Search API and then parses results. Requires LLM: No Extra Parameters: serper_api_key For more information on this, see this page wikipedia Tool Name: Wikipedia Tool Description: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query. Notes: Uses the wikipedia Python package to call the MediaWiki API and then parses results. Requires LLM: No Extra Parameters: top_k_results podcast-api Tool Name: Podcast API Tool 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. Notes: A natural language connection to the Listen Notes Podcast API (https://www.PodcastAPI.com), specifically the /search/ endpoint. Requires LLM: Yes Extra Parameters: listen_api_key (your api key to access this endpoint) openweathermap-api Tool Name: OpenWeatherMap Tool Description: A wrapper around OpenWeatherMap API. Useful for fetching current weather information for a specified location. Input should be a location string (e.g. London,GB).
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/getting_started.html
f1de38e13416-4
Notes: A connection to the OpenWeatherMap API (https://api.openweathermap.org), specifically the /data/2.5/weather endpoint. Requires LLM: No Extra Parameters: openweathermap_api_key (your API key to access this endpoint) sleep Tool Name: Sleep Tool Description: Make agent sleep for some time. Requires LLM: No previous Tools next Defining Custom Tools Contents List of Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/getting_started.html
c367a91ffc9a-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?")
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/ddg.html
c367a91ffc9a-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/ddg.html
c367a91ffc9a-2
previous ChatGPT Plugins next File System Tools By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/ddg.html
c4c96b676a7e-0
.ipynb .pdf Bing Search Contents Number of results Metadata Results Bing Search# This notebook goes over how to use the bing search component. First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here. Then we will need to set some environment variables. import os os.environ["BING_SUBSCRIPTION_KEY"] = "" os.environ["BING_SEARCH_URL"] = "" from langchain.utilities import BingSearchAPIWrapper search = BingSearchAPIWrapper() search.run("python")
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bing_search.html
c4c96b676a7e-1
'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor. <b>Python</b> releases by version number: Release version Release date Click for more. <b>Python</b> 3.11.1 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.10.9 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.9.16 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.8.16 Dec. 6, 2022 Download Release Notes. <b>Python</b> 3.7.16 Dec. 6, 2022 Download Release Notes. In this lesson, we will look at the += operator in <b>Python</b> and see how it works with several simple examples.. The operator ‘+=’ is a shorthand for the addition assignment operator.It adds two values and assigns the sum to a variable (left operand). W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, <b>Python</b>, SQL, Java, and many, many more. This tutorial introduces the reader informally to the basic concepts and features of the <b>Python</b> language and system. It helps to have a <b>Python</b> interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bing_search.html
c4c96b676a7e-2
self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see The <b>Python</b> Standard ... <b>Python</b> is a general-purpose, versatile, and powerful programming language. It&#39;s a great first language because <b>Python</b> code is concise and easy to read. Whatever you want to do, <b>python</b> can do it. From web development to machine learning to data science, <b>Python</b> is the language for you. To install <b>Python</b> using the Microsoft Store: Go to your Start menu (lower left Windows icon), type &quot;Microsoft Store&quot;, select the link to open the store. Once the store is open, select Search from the upper-right menu and enter &quot;<b>Python</b>&quot;. Select which version of <b>Python</b> you would like to use from the results under Apps. Under the “<b>Python</b> Releases for Mac OS X” heading, click the link for the Latest <b>Python</b> 3 Release - <b>Python</b> 3.x.x. As of this writing, the latest version was <b>Python</b> 3.8.4. Scroll to the bottom and click macOS 64-bit installer to start the download. When the installer is finished downloading, move on to the next step. Step 2: Run the Installer'
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bing_search.html
c4c96b676a7e-3
Number of results# You can use the k parameter to set the number of results search = BingSearchAPIWrapper(k=1) search.run("python") 'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor.' Metadata Results# Run query through BingSearch 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 = BingSearchAPIWrapper() search.results("apples", 5) [{'snippet': 'Lady Alice. Pink Lady <b>apples</b> aren’t the only lady in the apple family. Lady Alice <b>apples</b> were discovered growing, thanks to bees pollinating, in Washington. They are smaller and slightly more stout in appearance than other varieties. Their skin color appears to have red and yellow stripes running from stem to butt.', 'title': '25 Types of Apples - Jessica Gavin', 'link': 'https://www.jessicagavin.com/types-of-apples/'}, {'snippet': '<b>Apples</b> can do a lot for you, thanks to plant chemicals called flavonoids. And they have pectin, a fiber that breaks down in your gut. If you take off the apple’s skin before eating it, you won ...', 'title': 'Apples: Nutrition &amp; Health Benefits - WebMD', 'link': 'https://www.webmd.com/food-recipes/benefits-apples'},
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bing_search.html
c4c96b676a7e-4
{'snippet': '<b>Apples</b> boast many vitamins and minerals, though not in high amounts. However, <b>apples</b> are usually a good source of vitamin C. Vitamin C. Also called ascorbic acid, this vitamin is a common ...', 'title': 'Apples 101: Nutrition Facts and Health Benefits', 'link': 'https://www.healthline.com/nutrition/foods/apples'}, {'snippet': 'Weight management. The fibers in <b>apples</b> can slow digestion, helping one to feel greater satisfaction after eating. After following three large prospective cohorts of 133,468 men and women for 24 years, researchers found that higher intakes of fiber-rich fruits with a low glycemic load, particularly <b>apples</b> and pears, were associated with the least amount of weight gain over time.', 'title': 'Apples | The Nutrition Source | Harvard T.H. Chan School of Public Health', 'link': 'https://www.hsph.harvard.edu/nutritionsource/food-features/apples/'}] previous Shell Tool next Brave Search Contents Number of results Metadata Results By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bing_search.html
2d747a9cb6cf-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 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/youtube.html
279c2126df90-0
.ipynb .pdf Requests Contents Inside the tool Requests# The web contains a lot of information that LLMs do not have access to. In order to easily let LLMs interact with that information, we provide a wrapper around the Python Requests module that takes in a URL and fetches data from that URL. from langchain.agents import load_tools requests_tools = load_tools(["requests_all"]) requests_tools [RequestsGetTool(name='requests_get', description='A portal to the internet. Use this when you need to get specific content from a website. Input should be a url (i.e. https://www.google.com). The output will be the text response of the GET request.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)), RequestsPostTool(name='requests_post', description='Use this when you want to POST to a website.\n Input should be a json string with two keys: "url" and "data".\n The value of "url" should be a string, and the value of "data" should be a dictionary of \n key-value pairs you want to POST to the url.\n Be careful to always use double quotes for strings in the json string\n The output will be the text response of the POST request.\n ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)),
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-1
RequestsPatchTool(name='requests_patch', description='Use this when you want to PATCH to a website.\n Input should be a json string with two keys: "url" and "data".\n The value of "url" should be a string, and the value of "data" should be a dictionary of \n key-value pairs you want to PATCH to the url.\n Be careful to always use double quotes for strings in the json string\n The output will be the text response of the PATCH request.\n ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)), RequestsPutTool(name='requests_put', description='Use this when you want to PUT to a website.\n Input should be a json string with two keys: "url" and "data".\n The value of "url" should be a string, and the value of "data" should be a dictionary of \n key-value pairs you want to PUT to the url.\n Be careful to always use double quotes for strings in the json string.\n The output will be the text response of the PUT request.\n ', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None)), RequestsDeleteTool(name='requests_delete', description='A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request.', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, requests_wrapper=TextRequestsWrapper(headers=None, aiosession=None))] Inside the tool# Each requests tool contains a requests wrapper. You can work with these wrappers directly below
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-2
Each requests tool contains a requests wrapper. You can work with these wrappers directly below # Each tool wrapps a requests wrapper requests_tools[0].requests_wrapper TextRequestsWrapper(headers=None, aiosession=None) from langchain.utilities import TextRequestsWrapper requests = TextRequestsWrapper() requests.get("https://www.google.com")
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-3
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-4
nonce="MXrF0nnIBPkxBza4okrgPA">(function(){window.google={kEI:\'TA9QZOa5EdTakPIPuIad-Ac\',kEXPI:\'0,1359409,6059,206,4804,2316,383,246,5,1129120,1197768,626,380097,16111,28687,22431,1361,12319,17581,4997,13228,37471,7692,2891,3926,213,7615,606,50058,8228,17728,432,3,346,1244,1,16920,2648,4,1528,2304,29062,9871,3194,13658,2980,1457,16786,5803,2554,4094,7596,1,42154,2,14022,2373,342,23024,6699,3112
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-5
,342,23024,6699,31123,4568,6258,23418,1252,5835,14967,4333,4239,3245,445,2,2,1,26632,239,7916,7321,60,2,3,15965,872,7830,1796,10008,7,1922,9779,36154,6305,2007,17765,427,20136,14,82,2730,184,13600,3692,109,2412,1548,4308,3785,15175,3888,1515,3030,5628,478,4,9706,1804,7734,2738,1853,1032,9480,2995,576,1041,5648,3722,2058,3048,2130,2365,662,476,958,87,111,5807,2,975,1167,891,3580,1439,1128,7343,426,
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-6
,1439,1128,7343,426,249,517,95,1102,14,696,1270,750,400,2208,274,2776,164,89,119,204,139,129,1710,2505,320,3,631,439,2,300,1645,172,1783,784,169,642,329,401,50,479,614,238,757,535,717,102,2,739,738,44,232,22,442,961,45,214,383,567,500,487,151,120,256,253,179,673,2,102,2,10,535,123,135,1685,5206695,190,2,20,50,198,5994221,2804424,3311,141,795,19735,1,1,346,5008,7,13,10,24,31,2,39,1,5,1,16,7,2,41,24
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-7
9,1,5,1,16,7,2,41,247,4,9,7,9,15,4,4,121,24,23944834,4042142,1964,16672,2894,6250,15739,1726,647,409,837,1411438,146986,23612960,7,84,93,33,101,816,57,532,163,1,441,86,1,951,73,31,2,345,178,243,472,2,148,962,455,167,178,29,702,1856,288,292,805,93,137,68,416,177,292,399,55,95,2566\',kBL:\'hw1A\',kOPI:89978449};google.sn=\'webhp\';google.kHL=\'en\';})();(function(){\nvar
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-8
h=this||self;function l(){return void 0!==window.google&&void 0!==window.google.kOPI&&0!==window.google.kOPI?window.google.kOPI:null};var m,n=[];function p(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||m}function q(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b}function r(a){/^http:/i.test(a)&&"https:"===window.location.protocol&&(google.ml&&google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a}\nfunction t(a,b,c,d,k){var e="";-1===b.search("&ei=")&&(e="&ei="+p(d),-1===b.search("&lei=")&&(d=q(d))&&(e+="&lei="+d));d="";var g=-1===b.search("&cshid=")&&"slh"!==a,f=[];f.push(["zx",Date.now().toString()]);h._cshid&&g&&f.push(["cshid",h._cshid]);c=c();null!=c&&f.push(["opi",c.toString()]);for(c=0;c<f.length;c++){if(0===c||0<c)d+="&";d+=f[c][0]+"="+f[c][1]}return"/"+(k||"gen_204")+"?atyp=i&ct="+String(a)+"&cad="+(b+e+d)};m=google.kEI;google.getEI=p;google.getLEI=q;google.ml=function(){return null};google.log=function(a,b,c,d,k,e){e=void
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-9
null};google.log=function(a,b,c,d,k,e){e=void 0===e?l:e;c||(c=t(a,b,e,d,k));if(c=r(c)){a=new Image;var g=n.length;n[g]=a;a.onerror=a.onload=a.onabort=function(){delete n[g]};a.src=c}};google.logUrl=function(a,b){b=void 0===b?l:b;return t("",a,b)};}).call(this);(function(){google.y={};google.sy=[];google.x=function(a,b){if(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.sx=function(a){google.sy.push(a)};google.lm=[];google.plm=function(a){google.lm.push.apply(google.lm,a)};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};google.bx=!1;google.lx=function(){};}).call(this);google.f={};(function(){\ndocument.documentElement.addEventListener("submit",function(b){var a;if(a=b.target){var c=a.getAttribute("data-submitfalse");a="1"===c||"q"===c&&!a.elements.q.value?!0:!1}else a=!1;a&&(b.preventDefault(),b.stopPropagation())},!0);document.documentElement.addEventListener("click",function(b){var a;a:{for(a=b.target;a&&a!==document.documentElement;a=a.parentElement)if("A"===a.tagName){a="1"===a.getAttribute("data-nohref");break a}a=!1}a&&b.preventDefault()},!0);}).call(this);</script><style>#gbar,#guser{font-size:13px;padding-top:1px
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-10
!important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}\n</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#1558d6}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}body{background:#fff;color:#000}a{color:#4b11a8;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#1558d6}a:visited{color:#4b11a8}.sblc{padding-top:5px}.sblc a{display:block;margin:2px
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-11
a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#f8f9fa;border:solid 1px;border-color:#dadce0 #70757a #70757a #dadce0;height:30px}.lsbb{display:block}#WqQANb a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#dadce0}.lst:focus{outline:none}</style><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){window.google.erd={jsr:1,bv:1785,de:true};\nvar h=this||self;var k,l=null!=(k=h.mei)?k:1,n,p=null!=(n=h.sdo)?n:!0,q=0,r,t=google.erd,v=t.jsr;google.ml=function(a,b,d,m,e){e=void 0===e?2:e;b&&(r=a&&a.message);if(google.dl)return google.dl(a,e,d),null;if(0>v){window.console&&console.error(a,d);if(-2===v)throw a;b=!1}else b=!a||!a.message||"Error loading script"===a.message||q>=l&&!m?!1:!0;if(!b)return null;q++;d=d||{};b=encodeURIComponent;var
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-12
null;q++;d=d||{};b=encodeURIComponent;var c="/gen_204?atyp=i&ei="+b(google.kEI);google.kEXPI&&(c+="&jexpid="+b(google.kEXPI));c+="&srcpg="+b(google.sn)+"&jsr="+b(t.jsr)+"&bver="+b(t.bv);var f=a.lineNumber;void 0!==f&&(c+="&line="+f);var g=\na.fileName;g&&(0<g.indexOf("-extension:/")&&(e=3),c+="&script="+b(g),f&&g===window.location.href&&(f=document.documentElement.outerHTML.split("\\n")[f],c+="&cad="+b(f?f.substring(0,300):"No script found.")));c+="&jsel="+e;for(var u in d)c+="&",c+=b(u),c+="=",c+=b(d[u]);c=c+"&emsg="+b(a.name+": "+a.message);c=c+"&jsst="+b(a.stack||"N/A");12288<=c.length&&(c=c.substr(0,12288));a=c;m||google.log(0,"",a);return a};window.onerror=function(a,b,d,m,e){r!==a&&(a=e instanceof Error?e:Error(a),void 0===d||"lineNumber"in a||(a.lineNumber=d),void 0===b||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,"SyntaxError"===a.name||"SyntaxError"===a.message.substring(0,11)||-1!==a.message.indexOf("Script error")?3:0));r=null;p&&q>=l&&(window.onerror=null)};})();</script></head><body bgcolor="#fff"><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-13
nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var src=\'/images/nav_logo229.png\';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}\nif (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}\n}\n})();</script><div id="mngb"><div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="https://www.google.com/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="https://maps.google.com/maps?hl=en&tab=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href="https://www.youtube.com/?tab=w1">YouTube</a> <a class=gb1 href="https://news.google.com/?tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="https://www.google.com/intl/en/about/products?tab=wh"><u>More</u> &raquo;</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.com/history/optout?hl=en" class=gb4>Web History</a>
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-14
class=gb4>Web History</a> | <a href="/preferences?hl=en" class=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/&ec=GAZAAQ" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div></div><center><br clear="all" id="lgpd"><div id="lga"><img alt="Google" height="92" src="/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png" style="padding:28px 0 14px" width="272" id="hplogo"><br><br></div><form action="/search" name="f"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%">&nbsp;</td><td align="center" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden"><div class="ds" style="height:32px;margin:4px 0"><input class="lst" style="margin:0;padding:5px 8px 0 6px;vertical-align:top;color:#000" autocomplete="off" value="" title="Google Search" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class="lsbb"><input class="lsb" value="Google
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-15
class="ds"><span class="lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class="ds"><span class="lsbb"><input class="lsb" id="tsuid_1" value="I\'m Feeling Lucky" name="btnI" type="submit"><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var id=\'tsuid_1\';document.getElementById(id).onclick = function(){if (this.form.q.value){this.checked = 1;if (this.form.iflsig)this.form.iflsig.disabled = false;}\nelse top.location=\'/doodles/\';};})();</script><input value="AOEireoAAAAAZFAdXGKCXWBK5dlWxPhh8hNPQz1s9YT6" name="iflsig" type="hidden"></span></span></td><td class="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en&amp;authuser=0">Advanced search</a></td></tr></table><input id="gbv" name="gbv" type="hidden" value="1"><script nonce="MXrF0nnIBPkxBza4okrgPA">(function(){var a,b="1";if(document&&document.getElementById)if("undefined"!=typeof XMLHttpRequest)b="2";else if("undefined"!=typeof ActiveXObject){var c,d,e=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];for(c=0;d=e[c++];)try{new
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-16
ActiveXObject(d),b="2"}catch(h){}}a=b;if("2"==a&&-1==location.search.indexOf("&gbv=2")){var f=google.gbvu,g=document.getElementById("gbv");g&&(g.value=a);f&&window.setTimeout(function(){location.href=f},0)};}).call(this);</script></form><div id="gac_scont"></div><div style="font-size:83%;min-height:3.5em"><br><div id="prm"><style>.szppmdbYutt__middle-slot-promo{font-size:small;margin-bottom:32px}.szppmdbYutt__middle-slot-promo a.ZIeIlb{display:inline-block;text-decoration:none}.szppmdbYutt__middle-slot-promo img{border:none;margin-right:5px;vertical-align:middle}</style><div class="szppmdbYutt__middle-slot-promo" data-ved="0ahUKEwjmj7fr6dT-AhVULUQIHThDB38QnIcBCAQ"><a class="NKcBbd" href="https://www.google.com/url?q=https://blog.google/outreach-initiatives/diversity/asian-pacific-american-heritage-month-2023/%3Futm_source%3Dhpp%26utm_medium%3Downed%26utm_campaign%3Dapahm&amp;source=hpp&amp;id=19035152&amp;ct=3&amp;usg=AOvVaw1zrN82vzhoWl4hz1zZ4gLp&amp;sa=X&amp;ved=0ahUKEwjmj7fr6dT-AhVULUQIHThDB38Q8IcBCAU" rel="nofollow">Celebrate Asian Pacific American Heritage Month with Google</a></div></div></div><span
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-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>'
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
279c2126df90-21
previous Python REPL next SceneXplain Contents Inside the tool By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/requests.html
919448044e51-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 nla@zapier.com 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", "")
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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": "sreply@svb.com", "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": "sreply@svb.com", "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": "ankush@langchain.dev", "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."
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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):
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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...
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-6
overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS) > Entering new SimpleSequentialChain chain... {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "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": "sreply@svb.com", "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": "ankush@langchain.dev", "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]
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
919448044e51-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 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/zapier.html
620596164756-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 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/pubmed.html
674f2d57cc21-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:
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/human_tools.html
674f2d57cc21-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/human_tools.html
674f2d57cc21-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'?"
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/human_tools.html
674f2d57cc21-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/human_tools.html
674f2d57cc21-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.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/human_tools.html
674f2d57cc21-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 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/human_tools.html
dcd094e42eea-0
.ipynb .pdf Shell Tool Contents Use with Agents Shell Tool# Giving agents access to the shell is powerful (though risky outside a sandboxed environment). The LLM can use it to execute any shell commands. A common use case for this is letting the LLM interact with your local file system. from langchain.tools import ShellTool shell_tool = ShellTool() print(shell_tool.run({"commands": ["echo 'Hello World!'", "time"]})) Hello World! real 0m0.000s user 0m0.000s sys 0m0.000s /Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk. warnings.warn( Use with Agents# As with all tools, these can be given to an agent to accomplish more complex tasks. Let’s have the agent fetch some links from a web page. from langchain.chat_models import ChatOpenAI from langchain.agents import initialize_agent from langchain.agents import AgentType llm = ChatOpenAI(temperature=0) shell_tool.description = shell_tool.description + f"args {shell_tool.args}".replace("{", "{{").replace("}", "}}") self_ask_with_search = initialize_agent([shell_tool], llm, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True) self_ask_with_search.run("Download the langchain.com webpage and grep for all urls. Return only a sorted list of them. Be sure to use double quotes.") > Entering new AgentExecutor chain... Question: What is the task? Thought: We need to download the langchain.com webpage and extract all the URLs from it. Then we need to sort the URLs and return them. Action: ```
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bash.html
dcd094e42eea-1
Action: ``` { "action": "shell", "action_input": { "commands": [ "curl -s https://langchain.com | grep -o 'http[s]*://[^\" ]*' | sort" ] } } ``` /Users/wfh/code/lc/lckg/langchain/tools/shell/tool.py:34: UserWarning: The shell tool has no safeguards by default. Use at your own risk. warnings.warn( Observation: https://blog.langchain.dev/ https://discord.gg/6adMQxSpJS https://docs.langchain.com/docs/ https://github.com/hwchase17/chat-langchain https://github.com/hwchase17/langchain https://github.com/hwchase17/langchainjs https://github.com/sullivan-sean/chat-langchainjs https://js.langchain.com/docs/ https://python.langchain.com/en/latest/ https://twitter.com/langchainai Thought:The URLs have been successfully extracted and sorted. We can return the list of URLs as the final answer. Final Answer: ["https://blog.langchain.dev/", "https://discord.gg/6adMQxSpJS", "https://docs.langchain.com/docs/", "https://github.com/hwchase17/chat-langchain", "https://github.com/hwchase17/langchain", "https://github.com/hwchase17/langchainjs", "https://github.com/sullivan-sean/chat-langchainjs", "https://js.langchain.com/docs/", "https://python.langchain.com/en/latest/", "https://twitter.com/langchainai"] > Finished chain.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bash.html
dcd094e42eea-2
> Finished chain. '["https://blog.langchain.dev/", "https://discord.gg/6adMQxSpJS", "https://docs.langchain.com/docs/", "https://github.com/hwchase17/chat-langchain", "https://github.com/hwchase17/langchain", "https://github.com/hwchase17/langchainjs", "https://github.com/sullivan-sean/chat-langchainjs", "https://js.langchain.com/docs/", "https://python.langchain.com/en/latest/", "https://twitter.com/langchainai"]' previous AWS Lambda API next Bing Search Contents Use with Agents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/bash.html
8a2d3d793670-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/gradio_tools.html
8a2d3d793670-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/gradio_tools.html
8a2d3d793670-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/gradio_tools.html
8a2d3d793670-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 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/gradio_tools.html
edc58f4ae122-0
.ipynb .pdf IFTTT WebHooks Contents Creating a webhook Configuring the “If This” Configuring the “Then That” Finishing up IFTTT WebHooks# This notebook shows how to use IFTTT Webhooks. From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services. Creating a webhook# Go to https://ifttt.com/create Configuring the “If This”# Click on the “If This” button in the IFTTT interface. Search for “Webhooks” in the search bar. Choose the first option for “Receive a web request with a JSON payload.” Choose an Event Name that is specific to the service you plan to connect to. This will make it easier for you to manage the webhook URL. For example, if you’re connecting to Spotify, you could use “Spotify” as your Event Name. Click the “Create Trigger” button to save your settings and create your webhook. Configuring the “Then That”# Tap on the “Then That” button in the IFTTT interface. Search for the service you want to connect, such as Spotify. Choose an action from the service, such as “Add track to a playlist”. Configure the action by specifying the necessary details, such as the playlist name, e.g., “Songs from AI”. Reference the JSON Payload received by the Webhook in your action. For the Spotify scenario, choose “{{JsonPayload}}” as your search query. Tap the “Create Action” button to save your action settings. Once you have finished configuring your action, click the “Finish” button to complete the setup. Congratulations! You have successfully connected the Webhook to the desired service, and you’re ready to start receiving data and triggering actions 🎉
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/ifttt.html
edc58f4ae122-1
service, and you’re ready to start receiving data and triggering actions 🎉 Finishing up# To get your webhook URL go to https://ifttt.com/maker_webhooks/settings Copy the IFTTT key value from there. The URL is of the form https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value. from langchain.tools.ifttt import IFTTTWebhook import os key = os.environ["IFTTTKey"] url = f"https://maker.ifttt.com/trigger/spotify/json/with/key/{key}" tool = IFTTTWebhook(name="Spotify", description="Add a song to spotify playlist", url=url) tool.run("taylor swift") "Congratulations! You've fired the spotify JSON event" previous Human as a tool next Metaphor Search Contents Creating a webhook Configuring the “If This” Configuring the “Then That” Finishing up By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/ifttt.html
dc38ca462716-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
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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–)',
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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, ...',
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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',
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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, '
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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 - '
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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',
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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},
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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',
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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,
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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',
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html
dc38ca462716-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,
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/tools/examples/google_serper.html