langchain icon indicating copy to clipboard operation
langchain copied to clipboard

Add ToolException that a tool can throw.

Open xming521 opened this issue 2 years ago • 2 comments

Add ToolException that a tool can throw

This is an optional exception that tool throws when execution error occurs. When this exception 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 pink on the console.It can be used like this:

from langchain.schema import ToolException
from langchain import LLMMathChain, SerpAPIWrapper, OpenAI
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool, StructuredTool, Tool, tool
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(temperature=0)
llm_math_chain = LLMMathChain(llm=llm, verbose=True)

class Error_tool:
    def run(self, s: str):
        raise ToolException('The current search tool is not available.')
    
def handle_tool_error(error) -> str:
    return "The following errors occurred during tool execution:"+str(error)

search_tool1 = Error_tool()
search_tool2 = SerpAPIWrapper()
tools = [
    Tool.from_function(
        func=search_tool1.run,
        name="Search_tool1",
        description="useful for when you need to answer questions about current events.You should give priority to using it.",
        handle_tool_error=handle_tool_error,
    ),
    Tool.from_function(
        func=search_tool2.run,
        name="Search_tool2",
        description="useful for when you need to answer questions about current events",
        return_direct=True,
    )
]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True,
                         handle_tool_errors=handle_tool_error)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")

image

Who can review?

  • @vowelparrot

xming521 avatar May 21 '23 08:05 xming521

This looks good! We want to have similar behavior in arun - would you be able to mirror what you've implemented there?

vowelparrot avatar May 22 '23 13:05 vowelparrot

could we add an example notebook as well

dev2049 avatar May 22 '23 18:05 dev2049

@dev2049 @vowelparrot Added documentation, supported the arun function, and made some adjustments.

xming521 avatar May 25 '23 02:05 xming521

@dev2049 Can you merge my code, please? Thank you.

xming521 avatar May 29 '23 04:05 xming521

thanks @xming521!

dev2049 avatar May 29 '23 20:05 dev2049