Source code for langchain.agents.mrkl.output_parser
importrefromtypingimportUnionfromlangchain_core.agentsimportAgentAction,AgentFinishfromlangchain_core.exceptionsimportOutputParserExceptionfromlangchain.agents.agentimportAgentOutputParserfromlangchain.agents.mrkl.promptimportFORMAT_INSTRUCTIONSFINAL_ANSWER_ACTION="Final Answer:"MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE=("Invalid Format: Missing 'Action:' after 'Thought:")MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE=("Invalid Format: Missing 'Action Input:' after 'Action:'")FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE=("Parsing LLM output produced both a final answer and a parse-able action:")
[docs]classMRKLOutputParser(AgentOutputParser):"""MRKL Output parser for the chat agent."""format_instructions:str=FORMAT_INSTRUCTIONS"""Default formatting instructions"""
[docs]defget_format_instructions(self)->str:"""Returns formatting instructions for the given output parser."""returnself.format_instructions
[docs]defparse(self,text:str)->Union[AgentAction,AgentFinish]:"""Parse the output from the agent into an AgentAction or AgentFinish object. Args: text: The text to parse. Returns: An AgentAction or AgentFinish object. Raises: OutputParserException: If the output could not be parsed. """includes_answer=FINAL_ANSWER_ACTIONintextregex=(r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)")action_match=re.search(regex,text,re.DOTALL)ifaction_matchandincludes_answer:iftext.find(FINAL_ANSWER_ACTION)<text.find(action_match.group(0)):# if final answer is before the hallucination, return final answerstart_index=text.find(FINAL_ANSWER_ACTION)+len(FINAL_ANSWER_ACTION)end_index=text.find("\n\n",start_index)returnAgentFinish({"output":text[start_index:end_index].strip()},text[:end_index])else:raiseOutputParserException(f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}")ifaction_match:action=action_match.group(1).strip()action_input=action_match.group(2)tool_input=action_input.strip(" ")# ensure if its a well formed SQL query we don't remove any trailing " charsiftool_input.startswith("SELECT ")isFalse:tool_input=tool_input.strip('"')returnAgentAction(action,tool_input,text)elifincludes_answer:returnAgentFinish({"output":text.split(FINAL_ANSWER_ACTION)[-1].strip()},text)ifnotre.search(r"Action\s*\d*\s*:[\s]*(.*?)",text,re.DOTALL):raiseOutputParserException(f"Could not parse LLM output: `{text}`",observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,llm_output=text,send_to_llm=True,)elifnotre.search(r"[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)",text,re.DOTALL):raiseOutputParserException(f"Could not parse LLM output: `{text}`",observation=MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE,llm_output=text,send_to_llm=True,)else:raiseOutputParserException(f"Could not parse LLM output: `{text}`")