Source code for langchain.agents.conversational_chat.output_parser
from__future__importannotationsfromtypingimportUnionfromlangchain_core.agentsimportAgentAction,AgentFinishfromlangchain_core.exceptionsimportOutputParserExceptionfromlangchain_core.utils.jsonimportparse_json_markdownfromlangchain.agentsimportAgentOutputParserfromlangchain.agents.conversational_chat.promptimportFORMAT_INSTRUCTIONS# Define a class that parses output for conversational agents
[docs]classConvoOutputParser(AgentOutputParser):"""Output parser for the conversational 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]:"""Attempts to parse the given text into an AgentAction or AgentFinish. Raises: OutputParserException if parsing fails. """try:# Attempt to parse the text into a structured format (assumed to be JSON# stored as markdown)response=parse_json_markdown(text)# If the response contains an 'action' and 'action_input'if"action"inresponseand"action_input"inresponse:action,action_input=response["action"],response["action_input"]# If the action indicates a final answer, return an AgentFinishifaction=="Final Answer":returnAgentFinish({"output":action_input},text)else:# Otherwise, return an AgentAction with the specified action and# inputreturnAgentAction(action,action_input,text)else:# If the necessary keys aren't present in the response, raise an# exceptionraiseOutputParserException(f"Missing 'action' or 'action_input' in LLM output: {text}")exceptExceptionase:# If any other exception is raised during parsing, also raise an# OutputParserExceptionraiseOutputParserException(f"Could not parse LLM output: {text}")frome