[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]defget_format_instructions(self)->str:"""Returns formatting instructions for the given output parser."""returnself.format_instructions
[docs]defparse(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)else:returnAgentAction(response["action"],response.get("action_input",{}),text)else:returnAgentFinish({"output":text},text)exceptExceptionase:raiseOutputParserException(f"Could not parse LLM output: {text}")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."""