[docs]classChatOutputParser(AgentOutputParser):"""Output parser for the chat agent."""format_instructions:str=FORMAT_INSTRUCTIONS"""Default formatting instructions"""pattern:Pattern=re.compile(r"^.*?`{3}(?:json)?\n(.*?)`{3}.*?$",re.DOTALL)"""Regex pattern to parse the output."""
[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. ValueError: If the action could not be found. """includes_answer=FINAL_ANSWER_ACTIONintexttry:found=self.pattern.search(text)ifnotfound:# Fast fail to parse Final Answer.raiseValueError("action not found")action=found.group(1)response=json.loads(action.strip())includes_action="action"inresponseifincludes_answerandincludes_action:raiseOutputParserException("Parsing LLM output produced a final answer "f"and a parse-able action: {text}")returnAgentAction(response["action"],response.get("action_input",{}),text)exceptExceptionasexc:ifnotincludes_answer:raiseOutputParserException(f"Could not parse LLM output: {text}")fromexcoutput=text.split(FINAL_ANSWER_ACTION)[-1].strip()returnAgentFinish({"output":output},text)