[docs]classStructuredChatOutputParser(AgentOutputParser):"""Output parser for the structured chat agent."""format_instructions:str=FORMAT_INSTRUCTIONS"""Default formatting instructions"""pattern:Pattern=re.compile(r"```(?:json\s+)?(\W.*?)```",re.DOTALL)"""Regex pattern to parse the output."""
[docs]@overridedefget_format_instructions(self)->str:"""Returns formatting instructions for the given output parser."""returnself.format_instructions
[docs]@overridedefparse(self,text:str)->Union[AgentAction,AgentFinish]:try:action_match=self.pattern.search(text)ifaction_matchisnotNone:response=json.loads(action_match.group(1).strip(),strict=False)ifisinstance(response,list):# gpt turbo frequently ignores the directive to emit a single actionlogger.warning("Got multiple action responses: %s",response)response=response[0]ifresponse["action"]=="Final Answer":returnAgentFinish({"output":response["action_input"]},text)returnAgentAction(response["action"],response.get("action_input",{}),text,)returnAgentFinish({"output":text},text)exceptExceptionase:msg=f"Could not parse LLM output: {text}"raiseOutputParserException(msg)frome
[docs]classStructuredChatOutputParserWithRetries(AgentOutputParser):"""Output parser with retries for the structured chat agent."""base_parser:AgentOutputParser=Field(default_factory=StructuredChatOutputParser)"""The base parser to use."""output_fixing_parser:Optional[OutputFixingParser]=None"""The output fixing parser to use."""
[docs]@overridedefparse(self,text:str)->Union[AgentAction,AgentFinish]:try:ifself.output_fixing_parserisnotNone:returnself.output_fixing_parser.parse(text)returnself.base_parser.parse(text)exceptExceptionase:msg=f"Could not parse LLM output: {text}"raiseOutputParserException(msg)frome
[docs]@classmethoddeffrom_llm(cls,llm:Optional[BaseLanguageModel]=None,base_parser:Optional[StructuredChatOutputParser]=None,)->StructuredChatOutputParserWithRetries:"""Create a StructuredChatOutputParserWithRetries from a language model. Args: llm: The language model to use. base_parser: An optional StructuredChatOutputParser to use. Returns: An instance of StructuredChatOutputParserWithRetries. """ifllmisnotNone:base_parser=base_parserorStructuredChatOutputParser()output_fixing_parser:OutputFixingParser=OutputFixingParser.from_llm(llm=llm,parser=base_parser,)returncls(output_fixing_parser=output_fixing_parser)ifbase_parserisnotNone:returncls(base_parser=base_parser)returncls()