.ipynb
.pdf
Handle Parsing Errors
 Contents 
Setup
Error
Default error handling
Custom Error Message
Custom Error Function
Handle Parsing Errors#
Occasionally the LLM cannot determine what step to take because it outputs format in incorrect form to be handled by the output parser. In this case, by default the agent errors. But you can easily control this functionality with handle_parsing_errors! Let’s explore how.
Setup#
from langchain import OpenAI, LLMMathChain, SerpAPIWrapper, SQLDatabase, SQLDatabaseChain
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.agents.types import AGENT_TO_CLASS
search = SerpAPIWrapper()
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events. You should ask targeted questions"
    ),
]
Error#
In this scenario, the agent will error (because it fails to output an Action string)
mrkl = initialize_agent(
    tools, 
    ChatOpenAI(temperature=0), 
    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, 
    verbose=True,
)
mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action")
> Entering new AgentExecutor chain...
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
File ~/workplace/langchain/langchain/agents/chat/output_parser.py:21, in ChatOutputParser.parse(self, text)
     20 try:
---> 21     action = text.split("```")[1]
     22     response = json.loads(action.strip())
IndexError: list index out of range
rtdocs_stable/api.python.langchain.com/en/stable/modules/agents/agent_executors/examples/handle_parsing_errors.html